gpt4 book ai didi

javascript - 将 post 请求从 express js 服务器发送到另一个 express js 服务器?

转载 作者:行者123 更新时间:2023-11-30 21:12:31 25 4
gpt4 key购买 nike

我有一个运行在端口 3000 和 4000 上的 express js 服务器并想从服务器 3000 向服务器 4000 发送一个 post 请求

我试过这个:

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: First argument must be a string or Buffer at ClientRequest.OutgoingMessage.write (_http_outgoing.js:456:11) at Request.write (D:\restfullApi\examineerapi\node_modules\request\request.js‌​:1514:27) at end (D:\restfullApi\examineerapi\node_modules\request\request.js‌​:552:18) at Immediate. (D:\restfullApi\examineerapi\node_modules\request\request.js‌​:581:7) at runCallback (timers.js:637:20) at tryOnImmediate (timers.js:610:5) at processImmediate [as _immediateCallback] (timers.js:582:5)

这并不像我想象的那样有效。请帮我解决这个问题。

最佳答案

有一个名为 http 的本地 Node 模块,您可以在您的案例中使用它。它看起来像这样:

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

关于javascript - 将 post 请求从 express js 服务器发送到另一个 express js 服务器?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45997158/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com