簡體   English   中英

如何通過NodeJS中的POST http.request傳遞響應參數(包括正文)

[英]How to pass response paramaters including body from POST http.request in NodeJS

我正在嘗試編寫一個基本的REST Post客戶端以與node.js一起使用,由於要使用REST API,我必須從響應中獲取詳細信息,包括cookie,以保持與服務器的REST會話狀態。 我的問題是,當res.on觸發PRINTME變量中的所有數據並將其返回到test.js console.log()時,從響應中提取json對象的最佳方法是什么。

test.js文件

var rest = require('./rest');
rest.request('http','google.com','/upload','data\n');
console.log('PRINTME='JSON.stringify(res.PRINTME));

rest.js模塊

exports.request = function (protocol, host, path, data, cookie){
var protocalTypes = {
    http: {
        module: require('http')
        , port: '80'
    }
    , https: {
        module: require('https')
        , port: '443'
    }
};

var protocolModule = protocalTypes[protocol].module;

var options = {
    host: host,
    port: protocalTypes[protocol].port,
    path: path,
    method: 'POST',
    headers: {
        'Content-Type': 'text/xml'
        , 'Content-Length': Buffer.byteLength(data)
        , 'Cookie': cookie||''
    }
};

console.log('cookies sent= '+options.headers.Cookie)

var req = protocolModule.request(options, function(res) {
    var PRINTME = res;
    console.log('STATUS: ' + res.statusCode);
    console.log('HEADERS: ' + JSON.stringify(res.headers));
    res.setEncoding('utf8');
    res.on('data', function (chunk) {
        PRINTME.body = chunk;
        console.log('BODY: ' + chunk);
    });
    res.on('close', function () {res.emit('end')});
});

req.on('error', function(e) {
    console.error('Request Failure: ' + e.message);
 });

req.write(data);
req.end();
};

使用像request這樣的包將幫助您簡化代碼。

以下是rest.js var request = require('request');

module.exports = function(protocol, host, path, data, cookie, done) { 

    var options = {
        host: host,
        port: protocalTypes[protocol].port,
        path: path,
        method: 'POST',
        headers: {
            'Content-Type': 'text/xml',
            'Content-Length': Buffer.byteLength(data)
        },
        jar: true
    };

  request(options, function(err, resp, body) {
    if (err) return done(err);

    // call done, with first value being null to specify no errors occured
    return done(null, resp, body);
  });
}

jar設置為true將記住cookie,以備將來使用。

有關可用選項的更多信息,請參見此鏈接。

https://github.com/mikeal/request#requestoptions-callback

在另一個文件中使用此功能

var rest = require('./rest');

rest(... , function(err, resp, body){
   ...
});

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM