angularjs - 无法从 request.body 中提取发布数据

标签 angularjs node.js post express

这是我的 Angular 帖子请求:

    var webCall = $http({
               method: 'POST',
               url: '/validation',
               async : true,
               headers: {
                 'Content-Type': 'text/html'
               },
               data: {email: "abc@gmail.com"}});
   webCall.then(successHandler, errorHandler);

现在在我的nodejs服务器中,以下代码提取帖子数据:

app.post('/validation',function(req,res){
        req.on('data',function(data){
            console.log(data.toString());
        });

但是将请求正文安慰为:

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

控制台空对象。

最佳答案

可能的原因是您尚未添加(或在问题中显示)body-parser 中间件。

var bodyParser = require('body-parser');

// for parsing application/json
app.use(bodyParser.json());

// for parsing application/x-www-form-urlencoded
app.use(bodyParser.urlencoded({ extended: true }));

// for parsing multipart/form-data
app.use(multer());

在您期望接收的数据的路由之前添加相关中间件。就您而言,看起来您只需要第一个。另外,正如 @themyth92 所指出的,传递正确的 header 。

了解更多 here

关于angularjs - 无法从 request.body 中提取发布数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27266598/

相关文章:

javascript - 页面刷新时的 Angular 'Cannot GET' 路由

c# - Web API 不会将 bool 返回类型序列化为 json boolean 值

forms - 从 HTTP POST 调用下载 PDF

python Flask通过post和url发送数据

javascript - 通过 POST 调用 HTML Javascript 函数

dictionary - 如何将 POST 正文绑定(bind)到 map ?

angularjs - 如何将 ENV 变量的值注入(inject)到 Angular 模板中?

node.js - 为什么我无法在不调用脚本的情况下运行与我的 package.json 脚本相同的命令?

node.js - 我可以使用带有扩展参数的dynamicHelpers (expressjs)吗?

node.js - 使用 nodejs 发送 formData POST 请求