javascript - express POST req.body 解析器为空

标签 javascript angularjs node.js express

我在 Stack Overflow 上看到了类似的问题,并找到了使用以下方法的解决方案:

app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());

但是在打印日志时 req.body 是空白的。

app.js 内容:

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

// Define the port to run on
app.set('port', 8888);

app.use(express.static(path.join(__dirname, '/webapp/public')));

app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());

app.post('/getsolution', function (req, res) {
    console.log("request body is",req.body); //----req.body is blank here
});

angular的post请求代码如下

var parameters = JSON.stringify({ "urlPath": $location.path()});
$http.post('http://localhost:8888/getsolution/', parameters)
    .then(function (response) {
        if (response.data == "") {
            $window.location.href = 'http://localhost:8888/';
        } else {
            $scope.puzzle = response.data;
            $scope.puzzleSolution = response.data.solution;
        }
    }).catch(function onError(response) {
    $window.location.href = 'http://localhost:8888/';
});

控制台打印日志

request body is {}

当与下面的代码片段一起使用时,它不起作用

var app = angular.module('puzzleappsolution', [], function ($locationProvider) {
    $locationProvider.html5Mode(true);
 });//----->It is now working

但是在下面使用时它是有效的

var app = angular.module('puzzleappsolution', []);

最佳答案

Content-Type header 添加到您的 Angular 请求中:

$http.post('http://localhost:8888/getsolution/', parameters, {
    headers: {
        'Content-Type': 'application/json'
    }
})

关于javascript - express POST req.body 解析器为空,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45350347/

相关文章:

javascript - for 循环和 setTimeout 的范围和时间问题。

javascript - JS : need a css color code based on a string

javascript - angular-ui-router $stateChangeStart 事件在 Angular Webpack ES2015 组件构建中未触发

javascript - 将 javascript 缩小文件压缩为单个文件

javascript - 带有 Apache Tomcat 的 Express.js 服务器

javascript - 从客户端计算机读取文件的最简单方法?

javascript - 从 moment.js 获取时区列表

javascript - Angularjs:Html 呈现为文本

node.js - Nodejs Express 3框架 session 破坏问题

javascript - 无法填充数组并返回