我有一个在端口3000和4000上运行的快速js服务器 并希望从服务器3000向服务器4000发送发布请求
我试过了:
var post_options = {
url: "http://172.28.49.9:4000/quizResponse",
timeout: 20000,
method:"POST",
encoding: "application/json; charset=utf-8",
body : {data: formdata}
};
request(post_options,
function optionalCallback(err, httpResponse, body) {
if (err) {
console.log(err);
}else
console.log(body);
});
但是得到了这个错误:
TypeError:第一个参数必须是Request.write处的ClientRequest.OutgoingMessage.write(_http_outgoing.js:456:11)处的字符串或缓冲区(D:\ restfullApi \ examerapi \ node_modules \ request \ request.js:1514 :27)at Immediate(D:\ restfullApi \ examerapi \ node_modules \ request \ request.js:552:18)at Immediate。 (D:\ restfullApi \ examineerapi \ _doc_modules \ request_modules \ request \ _js:\ _对于命令,请在运行时,我在runCallback(timers.js:637:20),在tryOnImmediate(timers.js:610:5)处进行处理[作为_immediateCallback]( timers.js:582:5)
这不符合我的想法。请帮我解决这个问题。
答案 0 :(得分:1)
您可以在案例中使用名为http
的本机节点模块。它看起来像这样:
const http = require('http');
var postData = JSON.stringify({user: 'sample1'});
const options = {
hostname: '172.28.49.9',
port: 4000,
path: '/quizResponse',
method: 'POST',
headers: {
'content-type': 'application/json',
'accept': 'application/json'
}
};
const req = http.request(options, (res) => {
res.setEncoding('utf8');
res.on('data', (chunk) => {
console.log(`BODY: ${chunk}`);
});
res.on('end', () => {
console.log('No more data in response.');
});
});
req.on('error', (e) => {
console.error(`problem with request: ${e.message}`);
});
// write data to request body
req.write(postData);
req.end();
我建议你阅读文档:https://nodejs.org/api/http.html#http_http_request_options_callback