简体   繁体   English

Node.js HTTP请求返回正文/消息为空

[英]Node.js http request returning body/msg empty

I am trying to use this package https://www.npmjs.com/package/request to POST data and wait a response then post more data. 我正在尝试使用此程序包https://www.npmjs.com/package/request来发布数据并等待响应,然后发布更多数据。 But I am always getting body/msg as undefined and the code do not work for some reason. 但是我总是将body / msg设为未定义,并且由于某些原因该代码无法正常工作。

I have this code in browser : 我在浏览器中有以下代码:

$.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
    }); 

Here I get msg as {success: true, redirectTo: "https://255.255.255"} and I get redirected. 在这里,我得到的味精为{success: true, redirectTo: "https://255.255.255"}并且我被重定向。 This works. 这可行。

But, in node.js, this does not : 但是,在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); })

Body and msg, I get both empty. 身体和味精,我都空了。 console.log(err) return null console.log(err)返回null

/login is session based and it only supports application/x-www-form-urlencoded . /login基于会话,并且仅支持application/x-www-form-urlencoded Both seem to be sending the same type of data, everything identical. 两者似乎都在发送相同类型的数据,所有内容都相同。 I do not get whats wrong there :/ 我在那里没有什么错:/

I would appreciate any type of help. 我将不胜感激。 Thanks in advance 提前致谢

Edit : So I tried to use the proper callback arguments and I got this error : 403 Then I tried to use headers to simulate a broswer but I still get that error. 编辑:因此,我尝试使用正确的回调参数,并且收到此错误: 403然后,我尝试使用标头来模拟浏览器,但仍然收到该错误。

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

The format for the callback is (err,response,body); 回调的格式为(err,response,body); maybe that is why you are getting a empty body and response. 也许那就是为什么你得到一个空洞的身体和反应。 You can refer here for details. 您可以在这里查阅详细信息。

I think you are getting confused with Promise and non-promise request package. 我认为您对Promise和Non-Promise请求包感到困惑。 As per your example, $ajax returns Promiseified response and you directly get the data from the response of the ajax request. 按照您的示例, $ajax返回Promiseified响应,您可以直接从ajax请求的响应中获取数据。 You are expecting that request package should also give you data directly, which is not correct. 您期望request包也应该直接为您提供数据,这是不正确的。

Actually, you can solve your issue in two ways: 实际上,您可以通过两种方式解决问题:

Sol. 索尔 1: Use proper callback function arguments and you must get data in the third argument of the callback function. 1:使用正确的回调函数参数,并且必须在回调函数的第三个参数中获取数据。 Such as: 如:

var request = require('request');

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

Sol. 索尔 2: Use request-promise NPM package (download it from here ) and get pomisified response. 2:使用request-promise NPM封装(下载它从这里 ),并得到响应pomisified。 For example: 例如:

var request = require('request-promise');

const getData = async () => {
  return new Promise((resolve, reject) => {
    const options = {
      method: "POST",
      baseUrl: "https://255.255.255",
      uri: "/login",
      form: {
        username: "username",
        password: "password",
        autologin: "true",
        resolveWithFullResponse: true, // Returns full response. To get only data don't use this property or mark it false.
      }
    };

    // Get whole Response object.
    const response = await request(options);

    // Returns the Promise.Resolve or Reject based on response.
    if (response.statusCode < 200 || response.statusCode > 300) {
      const errorMsg = 'Error occurred while POSTing the request. Got status: ' + response.status;
      console.error(errorMsg);

      // Reject the promise. Should be caught.
      return reject(errorMsg);
    }

    const responseBody = response.body;
    console.log(responseBody);

    // Return the response.
    return resolve(responseBody);
  })
}

Above implementation will return a promise for the method getData() being called. 上面的实现将为调用方法getData()返回一个承诺。

NOTE: The statement const response = await request(options); 注意:语句const response = await request(options); will return whole response object if resolveWithFullResponse: true, is used in the options JSON object. 如果在options JSON对象中使用resolveWithFullResponse: true,将返回整个响应对象。 If you need only response body or data don't mention resolveWithFullResponse property in the options or assign value false to it. 如果只需要响应正文或数据,请不要在选项中提及resolveWithFullResponse属性,也不要为其分配值false By default the value of resolveWithFullResponse is false. 默认情况下, resolveWithFullResponse值为false。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM