关于前端:Express框架学习三

Express申请解决

3.1 构建模块化路由
 const express = require('express') 
 // 创立路由对象
 const home = express.Router();
 // 将路由和申请门路进行匹配
 app.use('/home', home);
  // 在home路由下持续创立路由
 home.get('/index', () => {
          //  /home/index
         res.send();
 });
 // home.js
 const home = express.Router(); 
 home.get('/index', () => {
     res.send();
 });
 module.exports = home;
 // admin.js
 const admin = express.Router();
 admin.get('/index', () => {
     res.send();
 });
 module.exports = admin;
 // app.js
 const home = require('./route/home.js');
 const admin = require('./route/admin.js');
 app.use('/home', home);
 app.use('/admin', admin);
3.2 GET参数的获取
 // 接管地址栏中问号前面的参数
 // 例如: http://localhost:3000/?name=zhangsan&age=30
 app.get('/', (req, res) => {
    console.log(req.query); // {"name": "zhangsan", "age": "30"}
 });
3.3 POST参数的获取

Express中接管post申请参数须要借助第三方包 body-parser。

 // 引入body-parser模块
 const bodyParser = require('body-parser');
 // 配置body-parser模块
 app.use(bodyParser.urlencoded({ extended: false }));
 // 接管申请
 app.post('/add', (req, res) => {
    // 接管申请参数
    console.log(req.body);
 }) 
3.4 Express路由参数
 app.get('/find/:id', (req, res) => { 
     console.log(req.params); // {id: 123} 
 });
localhost:3000/find/123
3.5 动态资源的解决

通过Express内置的express.static能够不便地托管动态文件,例如img、CSS、JavaScript 文件等。

 app.use(express.static('public'));

当初,public 目录上面的文件就能够拜访了。

http://localhost:3000/images/kitten.jpg
http://localhost:3000/css/style.css
http://localhost:3000/js/app.js
http://localhost:3000/images/bg.png
http://localhost:3000/hello.html 

评论

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

这个站点使用 Akismet 来减少垃圾评论。了解你的评论数据如何被处理