HTTP GET请求在节点中。js表达

时间:2022-08-19 16:59:04

How can I make an HTTP request from within node/express? I need to connect to another service. I am hoping the call is async and that the callback contains the remote servers response.

如何在node/express中发出HTTP请求?我需要连接到另一个服务。我希望调用是异步的,回调包含远程服务器响应。

12 个解决方案

#1


180  

Here's code from a sample of mine. It's async and returns a JSON object. It could do any get request. Note there's more optimal ways (just a sample) - for example, instead of concatenating the chunks you put into an array and join it etc... Hopefully, it gets you started in the right direction:

这是我的一个示例代码。它是异步的,返回一个JSON对象。它可以做任何get请求。注意,还有更优的方法(只是一个示例)——例如,不要将放入数组的块连接到数组中并将其连接到数组中……希望它能让你朝正确的方向开始:

var http = require("http");
var https = require("https");

/**
 * getJSON:  REST get request returning JSON object(s)
 * @param options: http options object
 * @param callback: callback to pass the results JSON object(s) back
 */
exports.getJSON = function(options, onResult)
{
    console.log("rest::getJSON");

    var port = options.port == 443 ? https : http;
    var req = port.request(options, function(res)
    {
        var output = '';
        console.log(options.host + ':' + res.statusCode);
        res.setEncoding('utf8');

        res.on('data', function (chunk) {
            output += chunk;
        });

        res.on('end', function() {
            var obj = JSON.parse(output);
            onResult(res.statusCode, obj);
        });
    });

    req.on('error', function(err) {
        //res.send('error: ' + err.message);
    });

    req.end();
};

It's called by creating an options objects like:

它通过创建一个选项来调用:

var options = {
    host: 'somesite.com',
    port: 443,
    path: '/some/path',
    method: 'GET',
    headers: {
        'Content-Type': 'application/json'
    }
};

and providing a callback function.

并提供一个回调函数。

For example, in a service, I require the rest module above and then do this.

例如,在服务中,我需要上面的rest模块,然后这样做。

rest.getJSON(options, function(statusCode, result) {
    // I could work with the result html/json here.  I could also just return it
    console.log("onResult: (" + statusCode + ")" + JSON.stringify(result));
    res.statusCode = statusCode;
    res.send(result);
});

UPDATE:

更新:

If you're looking for async await (linear no callback), promises, compile time support and intellisense, we create a lightweight http and rest client that fits that bill:

如果您正在寻找异步等待(线性无回调)、承诺、编译时支持和智能感知,我们将创建一个轻量级的http和rest客户端来满足这个需求:

Microsoft typed-rest-client

微软typed-rest-client

#2


85  

Try using the simple http.get(options, callback) function in node.js:

尝试使用简单的http。获取(选项,回调)函数:

var http = require('http');
var options = {
  host: 'www.google.com',
  path: '/index.html'
};

var req = http.get(options, function(res) {
  console.log('STATUS: ' + res.statusCode);
  console.log('HEADERS: ' + JSON.stringify(res.headers));

  // Buffer the body entirely for processing as a whole.
  var bodyChunks = [];
  res.on('data', function(chunk) {
    // You can process streamed parts here...
    bodyChunks.push(chunk);
  }).on('end', function() {
    var body = Buffer.concat(bodyChunks);
    console.log('BODY: ' + body);
    // ...and/or process the entire body here.
  })
});

req.on('error', function(e) {
  console.log('ERROR: ' + e.message);
});

There is also a general http.request(options, callback) function which allows you to specify the request method and other request details.

还有一个通用的http。请求(选项,回调)函数,允许您指定请求方法和其他请求细节。

#3


57  

Request and Superagent are pretty good libraries to use.

Request和Superagent是非常好的库。

Using request:

使用要求:

var request=require('request');

request.get('https://someplace',options,function(err,res,body){
  if(err) //TODO: handle err
  if(res.statusCode !== 200 ) //etc
  //TODO Do something with response
});

#4


27  

You can also use Requestify, a really cool and very simple HTTP client I wrote for nodeJS + it supports caching.

您还可以使用Requestify,这是我为nodeJS +编写的一个非常酷、非常简单的HTTP客户机,它支持缓存。

Just do the following for GET method request:

对于GET方法请求,只需执行以下操作:

var requestify = require('requestify');

requestify.get('http://example.com/api/resource')
  .then(function(response) {
      // Get the response body (JSON parsed or jQuery object for XMLs)
      response.getBody();
  }
);

#5


6  

Unirest is the best library I've come across for making HTTP requests from Node. It's aiming at being a multiplatform framework, so learning how it works on Node will serve you well if you need to use an HTTP client on Ruby, PHP, Java, Python, Objective C, .Net or Windows 8 as well. As far as I can tell the unirest libraries are mostly backed by existing HTTP clients (e.g. on Java, the Apache HTTP client, on Node, Mikeal's Request libary) - Unirest just puts a nicer API on top.

Unirest是我遇到的用于从Node发出HTTP请求的最佳库。它的目标是成为一个多平台框架,因此,如果您需要在Ruby、PHP、Java、Python、Objective C、. net或Windows 8上使用HTTP客户机,那么学习它在Node上的工作原理将非常有用。就我所知,unirest库主要由现有的HTTP客户端(例如,在Java、Apache HTTP客户端、节点上,Mikeal的请求libary)支持——unirest只是在上面添加了一个更好的API。

Here are a couple of code examples for Node.js:

以下是Node.js的一些代码示例:

var unirest = require('unirest')

// GET a resource
unirest.get('http://httpbin.org/get')
  .query({'foo': 'bar'})
  .query({'stack': 'overflow'})
  .end(function(res) {
    if (res.error) {
      console.log('GET error', res.error)
    } else {
      console.log('GET response', res.body)
    }
  })

// POST a form with an attached file
unirest.post('http://httpbin.org/post')
  .field('foo', 'bar')
  .field('stack', 'overflow')
  .attach('myfile', 'examples.js')
  .end(function(res) {
    if (res.error) {
      console.log('POST error', res.error)
    } else {
      console.log('POST response', res.body)
    }
  })

You can jump straight to the Node docs here

您可以直接跳转到这里的节点文档

#6


4  

Check out shred. It's a node HTTP client created and maintained by spire.io that handles redirects, sessions, and JSON responses. It's great for interacting with rest APIs. See this blog post for more details.

查看分解。它是由spire创建和维护的一个节点HTTP客户端。io处理重定向、会话和JSON响应。它非常适合与rest api交互。更多细节见此博客文章。

#7


4  

Check out httpreq: it's a node library I created because I was frustrated there was no simple http GET or POST module out there ;-)

查看httpreq:这是我创建的一个节点库,因为我对没有简单的http GET或POST模块感到沮丧;

#8


3  

This version is based on the initially proposed by bryanmac function which uses promises, better error handling, and is rewritten in ES6.

这个版本是基于bryanmac函数最初提出的,它使用承诺,更好的错误处理,并在ES6中重写。

let http = require("http"),
    https = require("https");

/**
 * getJSON:  REST get request returning JSON object(s)
 * @param options: http options object
 */
exports.getJSON = function(options)
{
    console.log('rest::getJSON');
    let reqHandler = +options.port === 443 ? https : http;

    return new Promise((resolve, reject) => {
        let req = reqHandler.request(options, (res) =>
        {
            let output = '';
            console.log('rest::', options.host + ':' + res.statusCode);
            res.setEncoding('utf8');

            res.on('data', function (chunk) {
                output += chunk;
            });

            res.on('end', () => {
                try {
                    let obj = JSON.parse(output);
                    // console.log('rest::', obj);
                    resolve({
                        statusCode: res.statusCode,
                        data: obj
                    });
                }
                catch(err) {
                    console.error('rest::end', err);
                    reject(err);
                }
            });
        });

        req.on('error', (err) => {
            console.error('rest::request', err);
            reject(err);
        });

        req.end();
    });
};

As a result you don't have to pass in a callback function, instead getJSON() returns a promise. In the following example the function is used inside of an ExpressJS route handler

因此,您不必传递回调函数,而是getJSON()返回一个承诺。在下面的示例中,该函数在ExpressJS路由处理程序中使用

router.get('/:id', (req, res, next) => {
    rest.getJSON({
        host: host,
        path: `/posts/${req.params.id}`,
        method: 'GET'
    }).then(({status, data}) => {
        res.json(data);
    }, (error) => {
        next(error);
    });
});

On error it delegates the error to the server error handling middleware.

错误时,它将错误委托给服务器错误处理中间件。

#9


1  

If you just need to make simple get requests and don't need support for any other HTTP methods take a look at: simple-get:

如果您只需要发出简单的get请求,而不需要对任何其他HTTP方法的支持,请查看:simple-get:

var get = require('simple-get');

get('http://example.com', function (err, res) {
  if (err) throw err;
  console.log(res.statusCode); // 200
  res.pipe(process.stdout); // `res` is a stream
});

#10


0  

Look at request module. Reference here http://www.sitepoint.com/making-http-requests-in-node-js/

看看请求模块。在这里引用http://www.sitepoint.com/making-http-requests-in-node-js/

#11


0  

Use reqclient: not designed for scripting purpose like request or many other libraries. Reqclient allows in the constructor specify many configurations useful when you need to reuse the same configuration again and again: base URL, headers, auth options, logging options, caching, etc. Also has useful features like query and URL parsing, automatic query encoding and JSON parsing, etc.

使用reqclient:不是为脚本目的而设计的,比如request或其他库。Reqclient允许在构造函数中指定许多有用的配置,当您需要反复重用相同的配置时:基本URL、头文件、auth选项、日志选项、缓存等。

The best way to use the library is create a module to export the object pointing to the API and the necessary configurations to connect with:

使用该库的最佳方式是创建一个模块来导出指向API的对象和连接所需的配置:

Module client.js:

模块client.js:

let RequestClient = require("reqclient").RequestClient

let client = new RequestClient({
  baseUrl: "https://myapp.com/api/v1",
  cache: true,
  auth: {user: "admin", pass: "secret"}
})

module.exports = client

And in the controllers where you need to consume the API use like this:

在需要使用API的控制器中

let client = require('client')
//let router = ...

router.get('/dashboard', (req, res) => {
  // Simple GET with Promise handling to https://myapp.com/api/v1/reports/clients
  client.get("reports/clients")
    .then(response => {
       console.log("Report for client", response.userId)  // REST responses are parsed as JSON objects
       res.render('clients/dashboard', {title: 'Customer Report', report: response})
    })
    .catch(err => {
      console.error("Ups!", err)
      res.status(400).render('error', {error: err})
    })
})

router.get('/orders', (req, res, next) => {
  // GET with query (https://myapp.com/api/v1/orders?state=open&limit=10)
  client.get({"uri": "orders", "query": {"state": "open", "limit": 10}})
    .then(orders => {
      res.render('clients/orders', {title: 'Customer Orders', orders: orders})
    })
    .catch(err => someErrorHandler(req, res, next))
})

router.delete('/orders', (req, res, next) => {
  // DELETE with params (https://myapp.com/api/v1/orders/1234/A987)
  client.delete({
    "uri": "orders/{client}/{id}",
    "params": {"client": "A987", "id": 1234}
  })
  .then(resp => res.status(204))
  .catch(err => someErrorHandler(req, res, next))
})

reqclient supports many features, but it has some that are not supported by other libraries: OAuth2 integration and logger integration with cURL syntax, and always returns native Promise objects.

reqclient支持许多特性,但是它有一些不受其他库支持的特性:OAuth2集成和logger与cURL语法的集成,并且总是返回本地的Promise对象。

#12


-1  

## you can use request module and promise in express to make any request ##
const promise                       = require('promise');
const requestModule                 = require('request');

const curlRequest =(requestOption) =>{
    return new Promise((resolve, reject)=> {
        requestModule(requestOption, (error, response, body) => {
            try {
                if (error) {
                    throw error;
                }
                if (body) {

                    try {
                        body = (body) ? JSON.parse(body) : body;
                        resolve(body);
                    }catch(error){
                        resolve(body);
                    }

                } else {

                    throw new Error('something wrong');
                }
            } catch (error) {

                reject(error);
            }
        })
    })
};

const option = {
    url : uri,
    method : "GET",
    headers : {

    }
};


curlRequest(option).then((data)=>{
}).catch((err)=>{
})

#1


180  

Here's code from a sample of mine. It's async and returns a JSON object. It could do any get request. Note there's more optimal ways (just a sample) - for example, instead of concatenating the chunks you put into an array and join it etc... Hopefully, it gets you started in the right direction:

这是我的一个示例代码。它是异步的,返回一个JSON对象。它可以做任何get请求。注意,还有更优的方法(只是一个示例)——例如,不要将放入数组的块连接到数组中并将其连接到数组中……希望它能让你朝正确的方向开始:

var http = require("http");
var https = require("https");

/**
 * getJSON:  REST get request returning JSON object(s)
 * @param options: http options object
 * @param callback: callback to pass the results JSON object(s) back
 */
exports.getJSON = function(options, onResult)
{
    console.log("rest::getJSON");

    var port = options.port == 443 ? https : http;
    var req = port.request(options, function(res)
    {
        var output = '';
        console.log(options.host + ':' + res.statusCode);
        res.setEncoding('utf8');

        res.on('data', function (chunk) {
            output += chunk;
        });

        res.on('end', function() {
            var obj = JSON.parse(output);
            onResult(res.statusCode, obj);
        });
    });

    req.on('error', function(err) {
        //res.send('error: ' + err.message);
    });

    req.end();
};

It's called by creating an options objects like:

它通过创建一个选项来调用:

var options = {
    host: 'somesite.com',
    port: 443,
    path: '/some/path',
    method: 'GET',
    headers: {
        'Content-Type': 'application/json'
    }
};

and providing a callback function.

并提供一个回调函数。

For example, in a service, I require the rest module above and then do this.

例如,在服务中,我需要上面的rest模块,然后这样做。

rest.getJSON(options, function(statusCode, result) {
    // I could work with the result html/json here.  I could also just return it
    console.log("onResult: (" + statusCode + ")" + JSON.stringify(result));
    res.statusCode = statusCode;
    res.send(result);
});

UPDATE:

更新:

If you're looking for async await (linear no callback), promises, compile time support and intellisense, we create a lightweight http and rest client that fits that bill:

如果您正在寻找异步等待(线性无回调)、承诺、编译时支持和智能感知,我们将创建一个轻量级的http和rest客户端来满足这个需求:

Microsoft typed-rest-client

微软typed-rest-client

#2


85  

Try using the simple http.get(options, callback) function in node.js:

尝试使用简单的http。获取(选项,回调)函数:

var http = require('http');
var options = {
  host: 'www.google.com',
  path: '/index.html'
};

var req = http.get(options, function(res) {
  console.log('STATUS: ' + res.statusCode);
  console.log('HEADERS: ' + JSON.stringify(res.headers));

  // Buffer the body entirely for processing as a whole.
  var bodyChunks = [];
  res.on('data', function(chunk) {
    // You can process streamed parts here...
    bodyChunks.push(chunk);
  }).on('end', function() {
    var body = Buffer.concat(bodyChunks);
    console.log('BODY: ' + body);
    // ...and/or process the entire body here.
  })
});

req.on('error', function(e) {
  console.log('ERROR: ' + e.message);
});

There is also a general http.request(options, callback) function which allows you to specify the request method and other request details.

还有一个通用的http。请求(选项,回调)函数,允许您指定请求方法和其他请求细节。

#3


57  

Request and Superagent are pretty good libraries to use.

Request和Superagent是非常好的库。

Using request:

使用要求:

var request=require('request');

request.get('https://someplace',options,function(err,res,body){
  if(err) //TODO: handle err
  if(res.statusCode !== 200 ) //etc
  //TODO Do something with response
});

#4


27  

You can also use Requestify, a really cool and very simple HTTP client I wrote for nodeJS + it supports caching.

您还可以使用Requestify,这是我为nodeJS +编写的一个非常酷、非常简单的HTTP客户机,它支持缓存。

Just do the following for GET method request:

对于GET方法请求,只需执行以下操作:

var requestify = require('requestify');

requestify.get('http://example.com/api/resource')
  .then(function(response) {
      // Get the response body (JSON parsed or jQuery object for XMLs)
      response.getBody();
  }
);

#5


6  

Unirest is the best library I've come across for making HTTP requests from Node. It's aiming at being a multiplatform framework, so learning how it works on Node will serve you well if you need to use an HTTP client on Ruby, PHP, Java, Python, Objective C, .Net or Windows 8 as well. As far as I can tell the unirest libraries are mostly backed by existing HTTP clients (e.g. on Java, the Apache HTTP client, on Node, Mikeal's Request libary) - Unirest just puts a nicer API on top.

Unirest是我遇到的用于从Node发出HTTP请求的最佳库。它的目标是成为一个多平台框架,因此,如果您需要在Ruby、PHP、Java、Python、Objective C、. net或Windows 8上使用HTTP客户机,那么学习它在Node上的工作原理将非常有用。就我所知,unirest库主要由现有的HTTP客户端(例如,在Java、Apache HTTP客户端、节点上,Mikeal的请求libary)支持——unirest只是在上面添加了一个更好的API。

Here are a couple of code examples for Node.js:

以下是Node.js的一些代码示例:

var unirest = require('unirest')

// GET a resource
unirest.get('http://httpbin.org/get')
  .query({'foo': 'bar'})
  .query({'stack': 'overflow'})
  .end(function(res) {
    if (res.error) {
      console.log('GET error', res.error)
    } else {
      console.log('GET response', res.body)
    }
  })

// POST a form with an attached file
unirest.post('http://httpbin.org/post')
  .field('foo', 'bar')
  .field('stack', 'overflow')
  .attach('myfile', 'examples.js')
  .end(function(res) {
    if (res.error) {
      console.log('POST error', res.error)
    } else {
      console.log('POST response', res.body)
    }
  })

You can jump straight to the Node docs here

您可以直接跳转到这里的节点文档

#6


4  

Check out shred. It's a node HTTP client created and maintained by spire.io that handles redirects, sessions, and JSON responses. It's great for interacting with rest APIs. See this blog post for more details.

查看分解。它是由spire创建和维护的一个节点HTTP客户端。io处理重定向、会话和JSON响应。它非常适合与rest api交互。更多细节见此博客文章。

#7


4  

Check out httpreq: it's a node library I created because I was frustrated there was no simple http GET or POST module out there ;-)

查看httpreq:这是我创建的一个节点库,因为我对没有简单的http GET或POST模块感到沮丧;

#8


3  

This version is based on the initially proposed by bryanmac function which uses promises, better error handling, and is rewritten in ES6.

这个版本是基于bryanmac函数最初提出的,它使用承诺,更好的错误处理,并在ES6中重写。

let http = require("http"),
    https = require("https");

/**
 * getJSON:  REST get request returning JSON object(s)
 * @param options: http options object
 */
exports.getJSON = function(options)
{
    console.log('rest::getJSON');
    let reqHandler = +options.port === 443 ? https : http;

    return new Promise((resolve, reject) => {
        let req = reqHandler.request(options, (res) =>
        {
            let output = '';
            console.log('rest::', options.host + ':' + res.statusCode);
            res.setEncoding('utf8');

            res.on('data', function (chunk) {
                output += chunk;
            });

            res.on('end', () => {
                try {
                    let obj = JSON.parse(output);
                    // console.log('rest::', obj);
                    resolve({
                        statusCode: res.statusCode,
                        data: obj
                    });
                }
                catch(err) {
                    console.error('rest::end', err);
                    reject(err);
                }
            });
        });

        req.on('error', (err) => {
            console.error('rest::request', err);
            reject(err);
        });

        req.end();
    });
};

As a result you don't have to pass in a callback function, instead getJSON() returns a promise. In the following example the function is used inside of an ExpressJS route handler

因此,您不必传递回调函数,而是getJSON()返回一个承诺。在下面的示例中,该函数在ExpressJS路由处理程序中使用

router.get('/:id', (req, res, next) => {
    rest.getJSON({
        host: host,
        path: `/posts/${req.params.id}`,
        method: 'GET'
    }).then(({status, data}) => {
        res.json(data);
    }, (error) => {
        next(error);
    });
});

On error it delegates the error to the server error handling middleware.

错误时,它将错误委托给服务器错误处理中间件。

#9


1  

If you just need to make simple get requests and don't need support for any other HTTP methods take a look at: simple-get:

如果您只需要发出简单的get请求,而不需要对任何其他HTTP方法的支持,请查看:simple-get:

var get = require('simple-get');

get('http://example.com', function (err, res) {
  if (err) throw err;
  console.log(res.statusCode); // 200
  res.pipe(process.stdout); // `res` is a stream
});

#10


0  

Look at request module. Reference here http://www.sitepoint.com/making-http-requests-in-node-js/

看看请求模块。在这里引用http://www.sitepoint.com/making-http-requests-in-node-js/

#11


0  

Use reqclient: not designed for scripting purpose like request or many other libraries. Reqclient allows in the constructor specify many configurations useful when you need to reuse the same configuration again and again: base URL, headers, auth options, logging options, caching, etc. Also has useful features like query and URL parsing, automatic query encoding and JSON parsing, etc.

使用reqclient:不是为脚本目的而设计的,比如request或其他库。Reqclient允许在构造函数中指定许多有用的配置,当您需要反复重用相同的配置时:基本URL、头文件、auth选项、日志选项、缓存等。

The best way to use the library is create a module to export the object pointing to the API and the necessary configurations to connect with:

使用该库的最佳方式是创建一个模块来导出指向API的对象和连接所需的配置:

Module client.js:

模块client.js:

let RequestClient = require("reqclient").RequestClient

let client = new RequestClient({
  baseUrl: "https://myapp.com/api/v1",
  cache: true,
  auth: {user: "admin", pass: "secret"}
})

module.exports = client

And in the controllers where you need to consume the API use like this:

在需要使用API的控制器中

let client = require('client')
//let router = ...

router.get('/dashboard', (req, res) => {
  // Simple GET with Promise handling to https://myapp.com/api/v1/reports/clients
  client.get("reports/clients")
    .then(response => {
       console.log("Report for client", response.userId)  // REST responses are parsed as JSON objects
       res.render('clients/dashboard', {title: 'Customer Report', report: response})
    })
    .catch(err => {
      console.error("Ups!", err)
      res.status(400).render('error', {error: err})
    })
})

router.get('/orders', (req, res, next) => {
  // GET with query (https://myapp.com/api/v1/orders?state=open&limit=10)
  client.get({"uri": "orders", "query": {"state": "open", "limit": 10}})
    .then(orders => {
      res.render('clients/orders', {title: 'Customer Orders', orders: orders})
    })
    .catch(err => someErrorHandler(req, res, next))
})

router.delete('/orders', (req, res, next) => {
  // DELETE with params (https://myapp.com/api/v1/orders/1234/A987)
  client.delete({
    "uri": "orders/{client}/{id}",
    "params": {"client": "A987", "id": 1234}
  })
  .then(resp => res.status(204))
  .catch(err => someErrorHandler(req, res, next))
})

reqclient supports many features, but it has some that are not supported by other libraries: OAuth2 integration and logger integration with cURL syntax, and always returns native Promise objects.

reqclient支持许多特性,但是它有一些不受其他库支持的特性:OAuth2集成和logger与cURL语法的集成,并且总是返回本地的Promise对象。

#12


-1  

## you can use request module and promise in express to make any request ##
const promise                       = require('promise');
const requestModule                 = require('request');

const curlRequest =(requestOption) =>{
    return new Promise((resolve, reject)=> {
        requestModule(requestOption, (error, response, body) => {
            try {
                if (error) {
                    throw error;
                }
                if (body) {

                    try {
                        body = (body) ? JSON.parse(body) : body;
                        resolve(body);
                    }catch(error){
                        resolve(body);
                    }

                } else {

                    throw new Error('something wrong');
                }
            } catch (error) {

                reject(error);
            }
        })
    })
};

const option = {
    url : uri,
    method : "GET",
    headers : {

    }
};


curlRequest(option).then((data)=>{
}).catch((err)=>{
})