【问题标题】:Unable to get $http.post request data in Node.js res.body无法在 Node.js res.body 中获取 $http.post 请求数据
【发布时间】:2016-03-05 04:26:20
【问题描述】:

我在一个项目中使用 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 中添加 content-type 标头:

headers : {'Content-Type': 'applicatio n/x-www-form-urlencoded'}

但没有得到请求数据。

编辑:

Node.js 代码:

router.post('/url',function(req,res){
    console.log(req.body)  
})

注意:开发人员工具的网络选项卡显示数据,我正在发送,在请求标头中正确,但 node.js 服务器未在req.body 中接收。 在 POSTman 中获取数据是正确的响应。

【问题讨论】:

  • 能不能分享一行nodejs代码
  • req.body 或 res.body
  • $http.post('url',{data:'data'}, function(res){console.log(res)})
  • 尝试使用 postman 或 rest 客户端来测试你的 api
  • @JayantPatil -$http.post 是 Angular 向节点 api 发送数据的方法。而 console.log(res.body) 在 node.js 服务器上用于获取请求数据 @server 端。我已经在邮递员中对其进行了测试,它显示了我的自定义错误,即没有收到请求数据,即使“开发者工具”的网络泛在请求标头中显示数据。

标签: angularjs json node.js http-post


【解决方案1】:

一些想法:

  • 可能是 URL 错误?确保您没有使用像 app.use('/api', router); 这样的前缀
  • Content-Type

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

【讨论】:

    【解决方案2】:

    我最好的猜测是您的角度 $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

    因此,作为上述问题中的代码示例,您缺少 /

    【讨论】:

    • 不,endpoint 是正确的,我用 dummy url 来解释问题,Node.js 能够得到请求。我使用的是 $.ajax,而不是 $http。数据格式仍然存在问题。所以我们更改了 node.js 代码。处理请求的数据。
    • 使用$.ajax后node.js得到了header数据,但是没有显示空数组。
    猜你喜欢
    • 2018-06-25
    • 2014-12-31
    • 2019-11-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-17
    • 2014-12-08
    相关资源
    最近更新 更多