Angularjs 请求未使用正文分析器显示数据

Angularjs 请求未使用正文分析器显示数据,angularjs,node.js,http,express,body-parser,Angularjs,Node.js,Http,Express,Body Parser,我正在从AngularJS客户端向NodeJS服务器发送一些JSON对象 这是我的客户代码,提出POST请求 customerData.endPoint = "customers"; $http.post('https://woocommerce-api-samarthagarwal-1.c9users.io/api', customerData) .then(function(response){ console.log(response) });

我正在从AngularJS客户端向NodeJS服务器发送一些JSON对象

这是我的客户代码,提出POST请求

customerData.endPoint = "customers";
$http.post('https://woocommerce-api-samarthagarwal-1.c9users.io/api', customerData)
     .then(function(response){
          console.log(response)
      });
这是我的服务器代码

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

var urlParser = bodyParser.urlencoded({ extended: true});
var jsonParser = bodyParser.json();

app.post('/api', jsonParser, function(request, response){
    response.setHeader("Access-Control-Allow-Origin", "*");
    console.log("body " + JSON.stringify(request.body));
    var endPoint = request.body.endPoint;
    console.log("POST on " + endPoint + " with Data " + (request.body.customer));
    });


var port = process.env.PORT;
var ip = process.env.IP
app.listen(port, ip,  function () {
  console.log('Server listening on ' + ip +':' + port);
});
但控制台上没有任何记录


非常感谢您的帮助。提前感谢。

您需要将
bodyParser
注册为express的中间件,否则它将不知道如何解析正文。在定义任何路由之前,需要使用该中间件

如果不将
bodyParser
注册为中间件,您的
请求.body
将始终是
{}
。因此,在执行
request.body.customer
时,该值将为
undefined
,并且整个
console.log()
语句将不会打印到控制台


我必须使用中间件为每个请求手动设置头

app.use(function(req, res, next) {
    req.headers['content-type'] = "application/json";
    next();
});

我在完成所有要求后使用了这段代码这应该是第一个工作的中间件。我希望它能帮助像我这样的人。

这是如何使用
body parser
所以请确保它实际安装正确,
npm install--save body parser
我重新安装并更新了你的代码。仍然在为
JSON.stringify(request.body)
@SamarthAgarwal获取
{}
,我清理了你的路线并用它更新了我的答案。看看这是否有帮助。我认为您没有收到内容类型:application/json header我可以使用中间件在每个请求上添加头吗?您可以记录request.headers吗?看起来您没有得到Content-Type:application/json,这会阻止bodyParser.json解析requestI-get
'Content-Type':'text/plain;请求头日志中的charset=UTF-8'
。在角度一侧将该请求头设置为
“application/json”
。它告诉你的服务器(即解析器)它正在发送一个JSON负载,这就是为什么你没有得到主体,如果你用curl调用呢?curl-X POST-d'{“endPoint”:“customers”}'-H'内容类型:application/json'The
curl
在服务器上显示了
customers
。我可以使用中间件将该头添加到每个请求中吗?实际上,如果我在我的角度代码中添加标题,我会得到一个飞行前错误。
app.use(function(req, res, next) {
    req.headers['content-type'] = "application/json";
    next();
});