表达POST req.body解析器为空

时间:2017-07-27 12:06:21

标签: 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的发布请求代码如下

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/';
});

控制台上的日志打印是

  

请求正文是{}

使用下面的代码段时,它无效

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

但是在下面使用时它正在工作

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

1 个答案:

答案 0 :(得分:1)

以角度

为您的请求添加Content-Type标头
$http.post('http://localhost:8888/getsolution/', parameters, {
    headers: {
        'Content-Type': 'application/json'
    }
})
相关问题