使用 Superagent 和 Express 4 接收 POST 请求数据
Receiving POST request data using Superagent and Express 4
Express -v : 4.13.3
超级代理-v:1.4
从我的应用程序前端发送 POST 请求的函数:
search: () => {
request.post('/api/search')
.set('Content-Type', 'application/json')
.send({hello: 'hello w'})
.end((err, response) => {
if (err) return console.error(err);
serveractions.receiveTest(response);
});
}
我的 Express 路由器文件:
var express = require('express');
var router = express.Router();
var bodyParser = require('body-parser');
router.use(bodyParser.urlencoded({extended: false}));
router.post('/api/search', (req, res, next) => {
console.log(req.body);
res.json({test: 'post received'});
});
module.exports = router;
路由器已成功发送和接收请求,但 req.body 始终为空,即使我正在使用 Superagent .send({hello: 'hello w'})
。我需要更改什么才能正确发送 json 对象并在我的路由器中接收它?
我找到答案了:
我将路由器文件更改为:
var express = require('express');
var router = express.Router();
var bodyParser = require('body-parser');
router.use( bodyParser.json() );
router.use(bodyParser.urlencoded({
extended: true
}));
router.post('/api/search', (req, res, next) => {
console.log(req.body);
res.json({test: 'post received'});
});
module.exports = router;
我的请求方式为:
searchRequest : (data) => {
request
.post('/api/search')
.send({ searchTerm : data })
.end((err, res) => {
if (err) console.log(err);
console.log(res);
})
}
Express -v : 4.13.3
超级代理-v:1.4
从我的应用程序前端发送 POST 请求的函数:
search: () => {
request.post('/api/search')
.set('Content-Type', 'application/json')
.send({hello: 'hello w'})
.end((err, response) => {
if (err) return console.error(err);
serveractions.receiveTest(response);
});
}
我的 Express 路由器文件:
var express = require('express');
var router = express.Router();
var bodyParser = require('body-parser');
router.use(bodyParser.urlencoded({extended: false}));
router.post('/api/search', (req, res, next) => {
console.log(req.body);
res.json({test: 'post received'});
});
module.exports = router;
路由器已成功发送和接收请求,但 req.body 始终为空,即使我正在使用 Superagent .send({hello: 'hello w'})
。我需要更改什么才能正确发送 json 对象并在我的路由器中接收它?
我找到答案了:
我将路由器文件更改为:
var express = require('express');
var router = express.Router();
var bodyParser = require('body-parser');
router.use( bodyParser.json() );
router.use(bodyParser.urlencoded({
extended: true
}));
router.post('/api/search', (req, res, next) => {
console.log(req.body);
res.json({test: 'post received'});
});
module.exports = router;
我的请求方式为:
searchRequest : (data) => {
request
.post('/api/search')
.send({ searchTerm : data })
.end((err, res) => {
if (err) console.log(err);
console.log(res);
})
}