简体   繁体   English

node.js从请求范围内检索主体

[英]nodejs retrieve body from inside request scope

I'm new to nodejs and javascript in general. 我是Nodejs和javascript的新手。 I believe this is an issue with the scope that I'm not understanding. 我认为这是我不了解的范围问题。

Given this example: ... ... 举这个例子:

if (url == '/'){
  var request = require('request');
  var body_text = ""; 
  request('http://www.google.com', function (error, response, body) {
    console.log('error:', error); 
    console.log('statusCode:', response && response.statusCode);  
    console.log('body:', body);
    body_text=body; 
  });
  console.log('This is the body:', body_text)
  //I need the value of body returned from the request here.. 
}

//OUTPUT 
This is the body: undefined

I need to be able to get the body from response back and then do some manipulation and I do not want to do all the implementation within the request function. 我需要能够从响应中获取主体,然后进行一些操作,并且我不想在request函数中进行所有实现。 Of course, if I move the log line into: 当然,如果我将日志行移至:

request( function { //here  })  

It works. 有用。 But I need to return the body in some way outside the request. 但是我需要在请求之外以某种方式退还尸体。 Any help would be appreciated. 任何帮助,将不胜感激。

You can't do that with callbacks because this will works asynchronously. 您不能通过回调来做到这一点,因为它将异步运行。

Work with callbacks is kind of normal in JS. 在JS中使用回调是很正常的。 But you can do better with Promises. 但是您可以通过Promises做得更好。

You can use the request-promise-native to do what you want with async/await. 您可以使用request-promise-native进行异步/等待操作。

async function requestFromClient(req, res) {
    const request = require('request-promise-native');
    const body_text = await request('http://www.google.com').catch((err) => {
      // always use catches to log errors or you will be lost
    })

    if (!body_text) {
      // sometimes you won't have a body and one of this case is when you get a request error
    }
    console.log('This is the body:', body_text)
    //I need the value of body returned from the request here.. 
}

As you see, you always must be in a function scope to use the async/await in promises. 如您所见,您始终必须处于函数作用域内才能在promise中使用async / await。

Recommendations: 建议:

  1. JS the right way JS正确的方法
  2. ES6 Fetures ES6功能
  3. JS clean coding JS干净编码
  4. More best practices... 更多最佳做法...
  5. Using promises 兑现承诺

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

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