如何在 Node.js 中进行远程 REST 调用?任何卷曲?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5643321/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 14:01:06  来源:igfitidea点击:

How to make remote REST call inside Node.js? any CURL?

restcurlnode.js

提问by murvinlai

In Node.js, other than using child process to make CURLcall, is there a way to make CURL call to remote server RESTAPI and get the return data?

Node.js 中,除了使用子进程进行CURL调用之外,有没有办法对远程服务器RESTAPI进行 CURL 调用并获取返回数据?

I also need to set up the request header to the remote RESTcall, and also query string as well in GET (or POST).

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

I find this one: http://blog.nodejitsu.com/jsdom-jquery-in-5-lines-on-nodejs

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

but it doesn't show any way to POST query string.

但它没有显示任何方式来发布查询字符串。

回答by Raynos

Look at http.request

看着 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();

回答by Matt Frear

How about using Request — Simplified HTTP client.

如何使用Request - Simplified HTTP client

Edit February 2020: Request has been deprecated so you probably shouldn't use it any more.

2020 年 2 月编辑:请求已被弃用,因此您可能不应再使用它。

Here's a GET:

这是一个GET:

var request = require('request');
request('http://www.google.com', function (error, response, body) {
    if (!error && response.statusCode == 200) {
        console.log(body) // Print the google web page.
     }
})

OP also wanted a POST:

OP 还想要一个 POST:

request.post('http://service.com/upload', {form:{key:'value'}})

回答by Giulio Roggero

Look at http://isolasoftware.it/2012/05/28/call-rest-api-with-node-js/

查看http://isolaso​​ftware.it/2012/05/28/call-rest-api-with-node-js/

var https = require('https');

/**
 * HOW TO Make an HTTP Call - GET
 */
// options for GET
var optionsget = {
    host : 'graph.facebook.com', // here only the domain name
    // (no http/https !)
    port : 443,
    path : '/youscada', // the rest of the url with parameters if needed
    method : 'GET' // do GET
};

console.info('Options prepared:');
console.info(optionsget);
console.info('Do the GET call');

// do the GET request
var reqGet = https.request(optionsget, function(res) {
    console.log("statusCode: ", res.statusCode);
    // uncomment it for header details
//  console.log("headers: ", res.headers);


    res.on('data', function(d) {
        console.info('GET result:\n');
        process.stdout.write(d);
        console.info('\n\nCall completed');
    });

});

reqGet.end();
reqGet.on('error', function(e) {
    console.error(e);
});

/**
 * HOW TO Make an HTTP Call - POST
 */
// do a POST request
// create the JSON object
jsonObject = JSON.stringify({
    "message" : "The web of things is approaching, let do some tests to be ready!",
    "name" : "Test message posted with node.js",
    "caption" : "Some tests with node.js",
    "link" : "http://www.youscada.com",
    "description" : "this is a description",
    "picture" : "http://youscada.com/wp-content/uploads/2012/05/logo2.png",
    "actions" : [ {
        "name" : "youSCADA",
        "link" : "http://www.youscada.com"
    } ]
});

// prepare the header
var postheaders = {
    'Content-Type' : 'application/json',
    'Content-Length' : Buffer.byteLength(jsonObject, 'utf8')
};

// the post options
var optionspost = {
    host : 'graph.facebook.com',
    port : 443,
    path : '/youscada/feed?access_token=your_api_key',
    method : 'POST',
    headers : postheaders
};

console.info('Options prepared:');
console.info(optionspost);
console.info('Do the POST call');

// do the POST call
var reqPost = https.request(optionspost, function(res) {
    console.log("statusCode: ", res.statusCode);
    // uncomment it for header details
//  console.log("headers: ", res.headers);

    res.on('data', function(d) {
        console.info('POST result:\n');
        process.stdout.write(d);
        console.info('\n\nPOST completed');
    });
});

// write the json data
reqPost.write(jsonObject);
reqPost.end();
reqPost.on('error', function(e) {
    console.error(e);
});

/**
 * Get Message - GET
 */
// options for GET
var optionsgetmsg = {
    host : 'graph.facebook.com', // here only the domain name
    // (no http/https !)
    port : 443,
    path : '/youscada/feed?access_token=you_api_key', // the rest of the url with parameters if needed
    method : 'GET' // do GET
};

console.info('Options prepared:');
console.info(optionsgetmsg);
console.info('Do the GET call');

// do the GET request
var reqGet = https.request(optionsgetmsg, function(res) {
    console.log("statusCode: ", res.statusCode);
    // uncomment it for header details
//  console.log("headers: ", res.headers);


    res.on('data', function(d) {
        console.info('GET result after POST:\n');
        process.stdout.write(d);
        console.info('\n\nCall completed');
    });

});

reqGet.end();
reqGet.on('error', function(e) {
    console.error(e);
});

回答by saille

I use node-fetchbecause it uses the familiar (if you are a web developer) fetch() API. fetch() is the new way to make arbitrary HTTP requests from the browser.

我使用node-fetch是因为它使用了熟悉的(如果您是 Web 开发人员)fetch() API。fetch() 是从浏览器发出任意 HTTP 请求的新方法。

Yes I know this is a node js question, but don't we want to reduce the number of API's developers have to memorize and understand, and improve re-useability of our javascript code? Fetch is a standardso how about we converge on that?

是的,我知道这是一个 node js 问题,但我们难道不想减少 API 开发人员必须记住和理解的数量,并提高我们 javascript 代码的可重用性吗?Fetch 是一个标准,那么我们如何收敛呢?

The other nice thing about fetch() is that it returns a javascript Promise, so you can write async code like this:

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

Fetch supersedes XMLHTTPRequest. Here's some more info.

Fetch 取代XMLHTTPRequest。这里有更多信息

回答by swapnil_mishra

I have been using restlerfor making webservices call, works like charm and is pretty neat.

我一直在使用restler进行网络服务调用,工作起来很迷人,而且非常整洁。

回答by Yuci

Axios

阿克西奥斯

An example (axios_example.js) using Axios in Node.js:

在 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);

Be sure in your project directory you do:

确保在您的项目目录中执行以下操作:

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

You can then test the Node.js REST API using your browser at: http://localhost:5000/search?queryStr=xxxxxxxxx

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

Similarly you can do post, such as:

同样,您可以发布帖子,例如:

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

SuperAgent

超级代理

Similarly you can use 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));
});

And if you want to do basic authentication:

如果您想进行基本身份验证:

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:

参考:

回答by codemirror

To use latest Async/Await features

使用最新的 Async/Await 功能

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

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

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

//code

//代码

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

回答by Hardik Ranpariya

one another example - you need to install request module for that

另一个例子 - 您需要为此安装请求模块

var request = require('request');
function get_trustyou(trust_you_id, callback) {
    var options = {
        uri : 'https://api.trustyou.com/hotels/'+trust_you_id+'/seal.json',
        method : 'GET'
    }; 
    var res = '';
    request(options, function (error, response, body) {
        if (!error && response.statusCode == 200) {
            res = body;
        }
        else {
            res = 'Not Found';
        }
        callback(res);
    });
}

get_trustyou("674fa44c-1fbd-4275-aa72-a20f262372cd", function(resp){
    console.log(resp);
});

回答by Seb

var http = require('http');
var url = process.argv[2];

http.get(url, function(response) {
  var finalData = "";

  response.on("data", function (data) {
    finalData += data.toString();
  });

  response.on("end", function() {
    console.log(finalData.length);
    console.log(finalData.toString());
  });

});

回答by Jonatas Walker

I didn't find any with cURL so I wrote a wrapper around node-libcurland can be found at https://www.npmjs.com/package/vps-rest-client.

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

To make a POST is like so:

做一个 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));