无法在Node.js res.body中获取$ http.post请求数据
我正在使用Angular 1.3和node.js 0.12.2作为一个项目。 我正在使用node.js api
$http.post("url", request_data){}
在服务器端使用这个:
console.log(req.body)
但每次调用api时,都会得到request_data
空对象,无法得到问题所在。 我已经使用body_parser
像这样:
var bodyParser = require('body-parser'); app.use(bodyParser.json()); // support json encoded bodies app.use(bodyParser.urlencoded({ extended: true })); // support encoded bodies
也尝试添加angular度$ http中的内容types标题为:
headers : {'Content-Type': 'applicatio n/x-www-form-urlencoded'}
但没有得到请求数据。
编辑:
Node.js代码:
router.post('/url',function(req,res){ console.log(req.body) })
注意:开发工具的networking选项卡显示的数据,我正在发送,请求标头正确,但node.js服务器不在req.body
接收。 在POSTMAN获取数据是正确的响应。
一些想法:
- 也许一个URL错误? 确保你没有使用前缀
app.use('/api', router);
- 看看
Content-Type
:
应用程序/ x-www-form-urlencoded – > 'var1="SomeValue"&var2='+SomeVariable
application / json; charset = UTF-8 – > {var1:"SomeValue", var2:SomeVariable}
- 你可以更明确地使用
$http
:
$http({ url: '...', method: 'POST', headers: { 'Content-Type': 'application/x-www-form-urlencoded' }, data: 'var1="SomeValue"&var2='+SomeVariable });
我最好的猜测是你的angular度$ HTTP请求URL指向一个坏的终点。
Angularjs
// data to post nodejs server var _data = { 'message': 'Can I help you?' }; // angularjs $http post request $http.post('/api/url', _data).then(function(respond){ // if success console.log(respond); }, function(error){ // if an error console.error(error); });
的NodeJS
// router function function something(req, res) { // console.log the request body console.log(req.body); // respond JSON object var _respond = { 'status': 200 }; // expressjs respond a JSON with status code 200 res.status(200).json(_respond); } // register route URL router.post('/api/url', something);
请注意,代码结束点URL是相同的: / api / url
因此,作为你在上面的问题的代码示例,你错过了/