我有这个作为我的快速服务器的配置

app.use(app.router); 
app.use(express.cookieParser());
app.use(express.session({ secret: "keyboard cat" }));
app.set('view engine', 'ejs');
app.set("view options", { layout: true });
//Handles post requests
app.use(express.bodyParser());
//Handles put requests
app.use(express.methodOverride());

但是当我在我的路由中请求req.body.something时,我得到了一些错误,指出body是未定义的。下面是一个使用req的路由示例。身体:

app.post('/admin', function(req, res){
    console.log(req.body.name);
});

我读到这个问题是由缺乏app.use(express.bodyParser())引起的;但你可以看到,我把它叫做路线之前。

有线索吗?


当前回答

试试这个

npm i multer --save
const express = require('express');
const multer  = require('multer');
const upload = multer();
const app = express();

app.post('/test', upload.any(), (req, res) => {
  console.log('data', req.body);
  res.setHeader('Content-Type', 'application/json');
  res.send(req.body);
});

其他回答

最新版本的Express (4.x)将中间件从核心框架中分离出来。如果需要正文解析器,则需要单独安装它

npm install body-parser --save

然后在代码中这样做

var bodyParser = require('body-parser')
var app = express()

// parse application/x-www-form-urlencoded
app.use(bodyParser.urlencoded({ extended: false }))

// parse application/json
app.use(bodyParser.json())

添加到你的app.js中

在路由器调用之前

const app = express();
app.use(express.json());

如果你使用一些外部工具来发出请求,请确保添加头文件:

内容类型:application / json

使用这一行在任何get或post请求之前在顶部进行适当的解析:

app.use(express.json()) 

它将json数据解析为Javascript对象。

You have to check following things for that:-
1. app.use(bodyParser.urlencoded({ extended: false }))

// parse application/json
app.use(bodyParser.json())
Implement body parser in your app.

2. Check headers in postman its should be based on your rest api's, like if your Content-Type: application/json it should be defined in your postman headers.