首页 > 解决方案 > 如何在 node.js 中使用 bodyparser

问题描述

我什么时候在我的代码中使用 bodyparser?

const express = require('express');
const bodyparser = require('body-parser');
const app = express();
app.set('views',__dirname+'/public/pages/');
app.set('view engine','twig');
// parse application/x-www-form-urlencoded
app.use(bodyParser.urlencoded({ extended: false }))

// parse application/json
app.use(bodyParser.json())
app.get('/',(req, res)=>{
    res.render('index',{title:"create user"})
})
app.post('/',(req, res)=>{
    console.log(req.body.username);
})
app.listen(8000, ()=>console.log('server is running at:http://localhost:8000'));

当我运行此代码时:错误在此处输入图像描述

标签: node.js

解决方案


我什么时候在我的代码中使用 bodyparser ?

该模块的 npm 页面显示,“Node.js 正文解析中间件。在处理程序之前在中间件中解析传入的请求正文,在 req.body 属性下可用。” 在这里阅读更多


推荐阅读