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

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

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

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


当前回答

我使用节点获取,因为它使用熟悉的(如果你是一个web开发人员)fetch() API。fetch()是从浏览器发出任意HTTP请求的新方法。

是的,我知道这是一个节点js的问题,但我们不希望减少API的开发者必须记住和理解的数量,并提高我们的javascript代码的可重用性吗?Fetch是一个标准,所以我们收敛一下如何?

fetch()的另一个好处是它返回一个javascript Promise,所以你可以像这样编写异步代码:

let fetch = require('node-fetch');

fetch('http://localhost', {
  method: 'POST',
  headers: {'Content-Type': 'application/json'},
  body: '{}'
}).then(response => {
  return response.json();
}).catch(err => {console.log(err);});

获取超级种子XMLHTTPRequest。这里有更多信息。

其他回答

我没有找到任何cURL,所以我写了一个node-libcurl包装器,可以在https://www.npmjs.com/package/vps-rest-client上找到。

POST是这样的:

var host = 'https://api.budgetvm.com/v2/dns/record';
var key = 'some___key';
var domain_id = 'some___id';

var rest = require('vps-rest-client');
var client = rest.createClient(key, {
  verbose: false
});

var post = {
  domain: domain_id,
  record: 'test.example.net',
  type: 'A',
  content: '111.111.111.111'
};

client.post(host, post).then(function(resp) {
  console.info(resp);

  if (resp.success === true) {
    // some action
  }
  client.close();
}).catch((err) => console.info(err));

警告:截至2020年2月11日,请求已完全弃用。

如果你使用form-data实现,更多信息请访问https://tanaikech.github.io/2017/07/27/multipart-post-request-using-node.js):

var fs = require('fs');
var request = require('request');
request.post({
  url: 'https://slack.com/api/files.upload',
  formData: {
    file: fs.createReadStream('sample.zip'),
    token: '### access token ###',
    filetype: 'zip',
    filename: 'samplefilename',
    channels: 'sample',
    title: 'sampletitle',
  },
}, function (error, response, body) {
  console.log(body);
});

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

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

如果你有Node.js 4.4+,看看reqclient,它允许你以cURL风格进行调用和记录请求,所以你可以很容易地在应用程序之外检查和重现调用。

返回Promise对象,而不是传递简单的回调函数,所以你可以以一种更“时尚”的方式处理结果,轻松地链接结果,并以一种标准的方式处理错误。还删除了每个请求的大量样板配置:基本URL、超时、内容类型格式、默认标头、URL中的参数和查询绑定,以及基本缓存特性。

这是一个如何初始化它的例子,调用并记录curl样式的操作:

var RequestClient = require("reqclient").RequestClient;
var client = new RequestClient({
    baseUrl:"http://baseurl.com/api/", debugRequest:true, debugResponse:true});
client.post("client/orders", {"client": 1234, "ref_id": "A987"},{"x-token": "AFF01XX"});

这将登录到控制台…

[Requesting client/orders]-> -X POST http://baseurl.com/api/client/orders -d '{"client": 1234, "ref_id": "A987"}' -H '{"x-token": "AFF01XX"}' -H Content-Type:application/json

当返回响应时……

[Response   client/orders]<- Status 200 - {"orderId": 1320934}

这是一个如何处理promise对象的响应的例子:

client.get("reports/clients")
  .then(function(response) {
    // Do something with the result
  }).catch(console.error);  // In case of error ...

当然,它可以用:npm install reqclient安装。