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

GET call with node js with headers

本文关键字:进行 GET 调用 js 节点 带头      更新时间:2023-09-26

这是我进行REST调用的代码。我已经尝试过POSTMAN rest调用,url和标头都可以。但使用node js,我无法执行此

我没有在这里给出真正的API密钥和url

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

输出究竟是什么?此外,在实际声明getheader之前,您可以在optionsget中引用getheader。

您应该查看请求库。