关于前端:Express框架学习三

36次阅读

共计 1311 个字符,预计需要花费 4 分钟才能阅读完成。

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 

正文完
 0