【问题标题】:Using Bulit-in Http Module instead of Request Module on Node.js在 Node.js 上使用内置的 Http 模块而不是请求模块
【发布时间】:2016-03-18 21:45:46
【问题描述】:

我想使用 Node.js 将表单数据发送到网络服务器,所以我使用了在 nodeland 中非常有名的“请求”模块。而且很酷,没有问题,但是由于某种原因(不支持写流编码),我不得不将其更改为内置模块“http”。

我认为下面的代码与将一些数据发布到网络服务器相同,当我使用“请求”模块时,没有问题所以可以得到200 response,发送数据成功。

但是在“http”模块中,我得到了一个重定向到另一个页面的302 response。和失败的发布数据。我不知道有什么问题,也许是 URL 问题,另一方面 http 使用 'host and path' ,请求使用 'url' 。我不知道我该如何解决这个问题,我卡了2天,如果你有一些提示,请告诉我..

谢谢。

通过使用“请求”模块

function postFormByRequestModule() {

   request({
        url: 'http://finance.naver.com/item/board_act.nhn',
        headers: { 'Content-Type': 'text/plain' },
        method: 'POST',
        form: {
            code:'000215',
            mode: 'write',
            title: 'This is Title',
            body:'This is body'
        }
    }, function (error, response, body) {
        if (error) {
            console.log(error);
        } else {
            console.log(response.statusCode, response.body);
        }
    });
}

通过使用“Http”模块

var postData = querystring.stringify({
            code:'000215',
            mode: 'write',
            title: 'This is Title',
            body:'This is body'
});


var options = {
    host: 'finance.naver.com',
    path: '/item/board_act.nhn',
    method: 'POST',
    headers: { 'Content-Type': 'text/plain', }
};

var req = http.request(options, function(res) {
    console.log('STATUS: ' + res.statusCode);
    res.setEncoding('utf8');
    res.on('data', function (chunk) {
        console.log('BODY: ' + chunk);
    });
    res.on('end', function() {
        console.log('No more data in response.')
    })
});

req.on('error', function(e) {
    console.log('problem with request: ' + e.message);
});

function postFormByBuiltInHttpModule() {
    req.write(postData);
    req.end();
}

【问题讨论】:

    标签: node.js http request


    【解决方案1】:

    内置的 http 客户端不会自动跟随,而 request 模块会(并且具有许多其他“高级”功能)。因此,如果您想继续使用内置客户端,则需要手动检查 res.headers.location 并在该 url 重试请求。

    【讨论】:

      猜你喜欢
      • 2018-01-05
      • 1970-01-01
      • 2023-03-05
      • 2019-04-14
      • 2011-09-28
      • 1970-01-01
      • 1970-01-01
      • 2013-04-24
      • 2013-05-05
      相关资源
      最近更新 更多