首页 > 解决方案 > Node.js http 请求返回 body/msg 为空

问题描述

我正在尝试使用此包https://www.npmjs.com/package/request来发布数据并等待响应然后发布更多数据。但我总是将 body/msg 设为未定义,并且代码由于某种原因无法正常工作。

我在浏览器中有这段代码:

$.ajax("/login",{ /// here i am in https://255.255.255 /// I am obscuring the real host ip

 data:{
   username:"username",
    password: "password",
     autologin:"true"},

 method:"POST"

}).done(function(msg) {
      console.log( msg );
       /// another $.ajax request here
    }); 

在这里,我得到了味精{success: true, redirectTo: "https://255.255.255"}并被重定向。这行得通。

但是,在 node.js 中,这不会:

var request = require('request');

request({
    method: "POST",
     baseUrl: "https://255.255.255",
      uri: "/login",
form: { 
      username: "username",
     password: "password",
    autologin: "true"}},
function(body, msg, err){ console.log(body); console.log(msg); })

身体和味精,我都空了。console.log(err)返回空

/login是基于会话的,它只支持application/x-www-form-urlencoded . 两者似乎都在发送相同类型的数据,一切都相同。我不明白那里有什么问题:/

我将不胜感激任何类型的帮助。提前致谢

编辑:所以我尝试使用正确的回调参数并收到此错误:403 然后我尝试使用标头来模拟浏览器,但我仍然收到该错误。

headers: {'user-agent': 'Mozilla/5.0'}
headers: {'user-agent': 'node.js'}

标签: javascriptjquerynode.jsajaxhttp

解决方案


回调的格式为 (err,response,body);也许这就是为什么你得到一个空的身体和回应。 您可以参考这里了解详细信息。


推荐阅读