使用带标头的节点js进行GET调用

时间:2014-10-15 10:16:03

标签: javascript node.js rest get

这是我执行REST调用的代码。我尝试过POSTMAN休息呼叫,网址和标题都可以。但是对于节点js,我无法做到这一点

我没有在这里提供真正的API密钥和网址

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

var getheaders = {
    'x-api-key' : 'diudnwod87wedh8778=',
    'content-type' : 'application/json;charset=UTF-8'

};

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

这是我的代码的参考:http://isolasoftware.it/2012/05/28/call-rest-api-with-node-js/

我已编辑了我的代码并且正在运行:

var http = require('http');
/**
 * HOW TO Make an HTTP Call - GET
 */
// options for GET
var getheaders = {
    'x-api-key' : 'diudnwod87wedh8778=',
    'content-type' : 'application/json;charset=UTF-8'

};

var optionsget = {
    host : 'abcd.com', // here only the domain name
    // (no http/https !)
    port : 80,
    path : '/edwde/wedwed/', // the rest of the url with parameters if needed
    headers : getheaders,
    method : 'GET' // do GET
};



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

// do the GET request
var reqGet = http.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);
});

2 个答案:

答案 0 :(得分:3)

输出到底是什么? 此外,在实际声明getheader之前,您在optionsget中引用了getheaders。

答案 1 :(得分:0)

您应该查看request库。