【发布时间】: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();
}
【问题讨论】: