abhimanyu
abhimanyu

Reputation: 165

send post request from express js server to another express js server?

I have an express js server running on port 3000 and 4000 and want to send a post request from server 3000 to server 4000

I tried this:

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);
});

But getting this error:

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)

This is not working as I thought. Please help me to solve this issue.

Upvotes: 3

Views: 10191

Answers (1)

Sebastian Kaczmarek
Sebastian Kaczmarek

Reputation: 8515

There is a native Node module called http which you can use in your case. It would look like this:

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();

I suggest you read the docs: https://nodejs.org/api/http.html#http_http_request_options_callback

Upvotes: 6

Related Questions