【问题标题】:send post request from express js server to another express js server?将 post 请求从 express js 服务器发送到另一个 express js 服务器?
【发布时间】:2018-02-10 08:05:14
【问题描述】:

我有一个在 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: 第一个参数必须是 ClientRequest.OutgoingMessage.write (_http_outgoing.js:456:11) 处的字符串或缓冲区 Request.write (D:\restfullApi\examineerapi\node_modules\request\request.js‌​:1514 :27) 在最后 (D:\restfullApi\examineerapi\node_modules\request\request.js‌​:552:18) 立即。 (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)

这不像我想象的那样工作。请帮我解决这个问题。

【问题讨论】:

  • 请在执行上述代码时添加您遇到的错误?
  • TypeError: 第一个参数必须是在 ClientRequest.OutgoingMessage.write (_http_outgoing.js:456:11) 在 Request.write (D:\restfullApi\examineerapi\node_modules\request\request .js:1514:27) 在结尾 (D:\restfullApi\examineerapi\node_modules\request\request.js:552:18) 在立即。 (D:\restfullApi\examineerapi\node_modules\request\request.js :581:7) 在 runCallback (timers.js:637:20) 在 tryOnImmediate (timers.js:610:5) 在 processImmediate [as _immediateCallback] (timers.js:582:5)
  • 对于正文,要成为json,您必须在request package 中设置json: true。请尝试在您的选项中添加json: true
  • Axios 也可以做到这一点:github.com/mzabriskie/axios

标签: javascript node.js express


【解决方案1】:

有一个名为 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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-11-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-01-06
    • 2021-06-05
    • 2021-06-18
    • 1970-01-01
    相关资源
    最近更新 更多