在Node.js中,除了使用子进程进行CURL调用之外,是否有一种方法可以对远程服务器REST API进行CURL调用并获得返回数据?

我还需要设置远程REST调用的请求头,以及在GET(或POST)中查询字符串。

我找到了这个:http://blog.nodejitsu.com/jsdom-jquery-in-5-lines-on-nodejs

但是它没有显示任何POST查询字符串的方法。


当前回答

Axios

在Node.js中使用Axios的示例(axios_example.js):

const axios = require('axios');
const express = require('express');
const app = express();
const port = process.env.PORT || 5000;

app.get('/search', function(req, res) {
    let query = req.query.queryStr;
    let url = `https://your.service.org?query=${query}`;

    axios({
        method:'get',
        url,
        auth: {
            username: 'the_username',
            password: 'the_password'
        }
    })
    .then(function (response) {
        res.send(JSON.stringify(response.data));
    })
    .catch(function (error) {
        console.log(error);
    });
});

var server = app.listen(port);

确保在你的项目目录中:

npm init
npm install express
npm install axios
node axios_example.js

然后,您可以在http://localhost:5000/search?queryStr=xxxxxxxxx上使用浏览器测试Node.js REST API

类似地,你可以做post,比如:

axios({
  method: 'post',
  url: 'https://your.service.org/user/12345',
  data: {
    firstName: 'Fred',
    lastName: 'Flintstone'
  }
});

SuperAgent

类似地,您可以使用SuperAgent。

superagent.get('https://your.service.org?query=xxxx')
.end((err, response) => {
    if (err) { return console.log(err); }
    res.send(JSON.stringify(response.body));
});

如果你想做基本的身份验证

superagent.get('https://your.service.org?query=xxxx')
.auth('the_username', 'the_password')
.end((err, response) => {
    if (err) { return console.log(err); }
    res.send(JSON.stringify(response.body));
});

Ref:

https://github.com/axios/axios https://www.twilio.com/blog/2017/08/http-requests-in-node-js.html

其他回答

使用最新的Async/Await特性

https://www.npmjs.com/package/request-promise-native

npm install --save request
npm install --save request-promise-native

/ /代码

async function getData (){
    try{
          var rp = require ('request-promise-native');
          var options = {
          uri:'https://reqres.in/api/users/2',
          json:true
        };

        var response = await rp(options);
        return response;
    }catch(error){
        throw error;
    }        
}

try{
    console.log(getData());
}catch(error){
    console.log(error);
}

我一直在使用restler进行webservices调用,工作起来很有魅力,而且很整洁。

Axios

在Node.js中使用Axios的示例(axios_example.js):

const axios = require('axios');
const express = require('express');
const app = express();
const port = process.env.PORT || 5000;

app.get('/search', function(req, res) {
    let query = req.query.queryStr;
    let url = `https://your.service.org?query=${query}`;

    axios({
        method:'get',
        url,
        auth: {
            username: 'the_username',
            password: 'the_password'
        }
    })
    .then(function (response) {
        res.send(JSON.stringify(response.data));
    })
    .catch(function (error) {
        console.log(error);
    });
});

var server = app.listen(port);

确保在你的项目目录中:

npm init
npm install express
npm install axios
node axios_example.js

然后,您可以在http://localhost:5000/search?queryStr=xxxxxxxxx上使用浏览器测试Node.js REST API

类似地,你可以做post,比如:

axios({
  method: 'post',
  url: 'https://your.service.org/user/12345',
  data: {
    firstName: 'Fred',
    lastName: 'Flintstone'
  }
});

SuperAgent

类似地,您可以使用SuperAgent。

superagent.get('https://your.service.org?query=xxxx')
.end((err, response) => {
    if (err) { return console.log(err); }
    res.send(JSON.stringify(response.body));
});

如果你想做基本的身份验证

superagent.get('https://your.service.org?query=xxxx')
.auth('the_username', 'the_password')
.end((err, response) => {
    if (err) { return console.log(err); }
    res.send(JSON.stringify(response.body));
});

Ref:

https://github.com/axios/axios https://www.twilio.com/blog/2017/08/http-requests-in-node-js.html

您可以使用curlrequest轻松设置请求的时间…你甚至可以在选项中设置头信息来“伪造”浏览器调用。

看看http.request

var options = {
  host: url,
  port: 80,
  path: '/resource?id=foo&bar=baz',
  method: 'POST'
};

http.request(options, function(res) {
  console.log('STATUS: ' + res.statusCode);
  console.log('HEADERS: ' + JSON.stringify(res.headers));
  res.setEncoding('utf8');
  res.on('data', function (chunk) {
    console.log('BODY: ' + chunk);
  });
}).end();