abh*_*nyu 3 javascript node.js express
我有一个在端口 3000 和 4000 上运行的 Express js 服务器\n并且想要从服务器 3000 向服务器 4000 发送 post 请求
\n\n我试过这个:
\n\nvar post_options = {\n url: "http://172.28.49.9:4000/quizResponse",\n timeout: 20000,\n method:"POST",\n encoding: "application/json; charset=utf-8",\n body : {data: formdata}\n};\nrequest(post_options,\nfunction optionalCallback(err, httpResponse, body) {\n if (err) {\n console.log(err);\n }else\n console.log(body);\n});\nRun Code Online (Sandbox Code Playgroud)\n\n但出现此错误:
\n\n\n\n\n类型错误:第一个参数必须是 Request.write 处 ClientRequest.OutgoingMessage.write (_http_outgoing.js:456:11) 处的字符串或缓冲区 (D:\\restfullApi\\examineerapi\\node_modules\\request\\request.js\ xe2\x80\x8c\xe2\x80\x8b:1514:27) 在末尾 (D:\\restfullApi\\examineerapi\\node_modules\\request\\request.js\xe2\x80\x8c\xe2\x80\x8b :552:18) 立即。(D:\\restfullApi\\examineerapi\\node_modules\\request\\request.js\xe2\x80\x8c\xe2\x80\x8b:581:7) 在 runCallback (timers.js:637:20) 在 tryOnImmediate (timers.js:610:5) 在 processImmediate [as _immediateCallback] (timers.js:582:5)
\n
这并不像我想象的那样工作。请帮我解决这个问题。
\n有一个名为的本机 Node 模块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();
Run Code Online (Sandbox Code Playgroud)
我建议您阅读文档:https://nodejs.org/api/http.html#http_http_request_options_callback
| 归档时间: |
|
| 查看次数: |
9681 次 |
| 最近记录: |