在 express.js 中解析传入请求
node.jsserver side programmingprogramming
为了在 http 请求中接收一些数据,我们在 URL 路径"/add-username"上添加一个表单:
app.use('/add-username', (req, res,next)=>{ res.send('<form action="/post-username" method="POST> <input type="text" name="username> <button type="submit> Send </button> </form>'); });
为了解析 http 请求,我们需要第三方库 body-parser:它是生产环境必需的依赖项
npm install -save body-parser
express js 提供了中间件使用函数,可以在添加中间件之前添加 body 解析器。
const http = require('http'); const express = require('express'); const bodyParser = require('body-parser'); const app = express(); app.use(bodyParser.urlencoded({extended: false}));
上面显示的 use(0 函数默认使用 next() 函数,因此 http 请求可以顺利传递到下一个中间件。
上面的解析器对于解析简单的表单数据(例如输入文本等)非常有用,但对于解析 JSON 文件,我们将使用不同的解析器。
现在,解析请求比使用核心 node.js 代码编写方式更简单。
Express.js 在 http 请求中提供了一个属性 body,它将返回请求数据。
控制台输出:on localhost: 3000/add-username
data: tutorials point
使用响应中的重定向函数可以轻松重定向请求。
完整的 App.js 文件显示在此处 −
const http = require('http'); const express = require('express'); const bodyParser = require('body-parser'); const app = express(); app.use(bodyParser.urlencoded({extended: false})); app.use('/', (req, res,next)=>{ next(); }); app.use('/add-username', (req, res,next)=>{ res.send('<form action="/post-username" method="POST"> <input type="text" name="username"> <button type="submit"> Send </button> </form>'); }); app.use('/post-username', (req, res, next)=>{ console.log('data: ', req.body.username); res.redirect('/'); }); app.use('/', (req, res,next)=>{ res.send('<h1> first midleware: Hello Tutorials Point </h1>'); }); const server = http.createServer(app); server.listen(3000);
安装任何第三方库后,应手动重新启动 nodemon 以使新库生效,而不是依赖可能无法正常工作的 nodemon 自动重启。