【发布时间】:2017-06-10 11:29:13
【问题描述】:
我在php 中有一个处理$_POST 数据的函数。
使用 curl 我可以像这样发送我的数据:
curl --data "request=value2" http://localhost/mywebsite/
在 php 中:
if (isset($_POST)) {
echo '<look>' . $_POST . '</look>';
exit;
}
使用 curl 后,我可以在控制台中查看输出 <look>Array</look>。
但是如何使用 node.js 调用上面的 post 请求
这是我迄今为止尝试过的:
const postData = querystring.stringify({
'request': 'value2'
});
// the post options
var optionspost = {
host: 'localhost',
path: 'mywebsite/?request=value2',
method : 'POST',
port : 80,
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
'Content-Length': Buffer.byteLength(postData)
}
};
console.info('Options prepared:');
//console.info(optionspost);
console.info('Do the POST call');
// do the POST call
var reqPost = http.request(optionspost, function(res) {
console.log("statusCode: ", res.statusCode);
// uncomment it for header details
//console.log("headers: ", res);
res.on('data', function(d) {
console.info('POST result:\n');
console.log(d);
var textChunk = d.toString('utf8');
console.log(textChunk);
console.info('\n\nPOST completed');
});
});
// write the json data
//reqPost.write(jsonObject);
reqPost.on('error', function(e) {
console.log("post error");
console.error(e);
});
reqPost.write(postData);
reqPost.end();
这是输出:
statusCode: 400
POST result:
<Buffer 3c 21 44 4f 43 54 59 50 45 20 48 54 4d 4c 20 50 55 42 4c 49 43 20 22 2d
2f 2f 49 45 54 46 2f 2f 44 54 44 20 48 54 4d 4c 20 32 2e 30 2f 2f 45 4e 22 3e .
. >
<!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML 2.0//EN">
<html><head>
<title>400 Bad Request</title>
</head><body>
<h1>Bad Request</h1>
<p>Your browser sent a request that this server could not understand.<br />
</p>
<hr>
<address>Apache/2.4.23 (Win64) PHP/5.6.25 Server at localhost Port 80</address>
</body></html>
POST completed
如何获得与 curl 相同的输出。请帮忙!
【问题讨论】: