I am having a function in php
which process $_POST data.
Using curl I can send my data like this:
curl --data "request=value2" http://localhost/mywebsite/
in php:
if (isset($_POST)) {
echo '<look>' . $_POST . '</look>';
exit;
}
I can view output <look>Array</look>
in console after using curl.
but how to call above post request using node.js
This is what I tried so far:
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();
This is output :
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
How to get same output as curl. please help!
via EmptyData
No comments:
Post a Comment