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

mur*_*lai 178 rest curl node.js

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

我还需要为远程REST调用设置请求标头,并在GET(或POST)中也查询字符串.

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

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

Ray*_*nos 207

看着 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();
Run Code Online (Sandbox Code Playgroud)

  • 需要注意的一点是,您不要在主机条目中放置http或https,例如var options = {host:graph.facebook.com ....} not {host:http:graph.facebook.com}.这使我绊倒了几个周期.(见下文).这些都是很好的答案.谢谢你们俩. (13认同)
  • 我可以指出,如果回复很长,使用res.on('data',..)是不够的.我相信正确的方法是让res.on('end'..)知道你什么时候收到了所有的数据.然后你可以处理. (9认同)
  • 那么,即使是POST,我还在查询字符串中附加数据? (3认同)
  • @murvinlai不确定.去阅读文档,源代码,HTTP规范.不是该地区的专家. (3认同)
  • 这是一个非常古老的答案 - 对于今天编写节点j的人来说,你肯定会使用https://www.npmjs.com/package/node-fetch或其他基于fetch标准的基于fetch API的软件包.请参阅下面的答案. (3认同)
  • 你能提到你是如何调用 http 模块的吗?要求('什么?') (3认同)

Mat*_*ear 90

如何使用Request - Simplified HTTP client.

这是一个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.
     }
})
Run Code Online (Sandbox Code Playgroud)

OP也想要一个POST:

request.post('http://service.com/upload', {form:{key:'value'}})
Run Code Online (Sandbox Code Playgroud)

  • 截至 2020 年 2 月 11 日,该请求已完全弃用。您可以在网站 https://github.com/request/request#deprecated 中看到它 (4认同)

小智 35

请看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);
});
Run Code Online (Sandbox Code Playgroud)

  • 设法通过使用var thed = JSON.parse(d)获取值; console.log("id为:"+ thed.data [0] .id); 但有一段时间我得到"意外的输入结束" (2认同)

sai*_*lle 28

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

是的我知道这是一个节点问题,但是我们不想减少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);});
Run Code Online (Sandbox Code Playgroud)

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

  • 注意:从 v17.5 开始,fetch() 将进入核心 NodeJS 运行时 https://fusebit.io/blog/node-fetch/ (2认同)

Yuc*_*uci 13

阿克西奥斯

在 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);
Run Code Online (Sandbox Code Playgroud)

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

npm init
npm install express
npm install axios
node axios_example.js
Run Code Online (Sandbox Code Playgroud)

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

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

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

超级代理

同样,您可以使用 SuperAgent。

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

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

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));
});
Run Code Online (Sandbox Code Playgroud)

参考:


swa*_*hra 11

我一直在使用restler进行webservices调用,像魅力一样工作,非常整洁.


Har*_*iya 5

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

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

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);
});
Run Code Online (Sandbox Code Playgroud)


cod*_*ror 5

使用最新的异步/等待功能

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

npm install --save request
npm install --save request-promise-native
Run Code Online (Sandbox Code Playgroud)

//码

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);
}
Run Code Online (Sandbox Code Playgroud)