简体   繁体   中英

How to pass post data in http request method

The following error prompts when my code executes.
It seems that body parameter could not be read.

missing required input JSON parameter requestType.

app.post('/compare', function (req, res, next) {
    var options = {
        host: 'hostname',
        port: 80,
        path: '/service',
        method: 'POST',
        headers: {
          'Accept': 'application/json',
          'Content-Type': 'application/json',
          'Authorization': "Basic " + new Buffer(username + ":" + pass).toString("base64")
        },
        body: JSON.stringify({
          requestType: 'createService'
        })
      };
   var httpreq = http.request(options, function (response) {
     response.on('data', function (chunk) {
       console.log("body: " + chunk);
     });
    response.on('end', function() {
      res.send('ok');
    })
   });
   httpreq.end();
});

I checked node's http modules latest documentation for request method.

It's options parameter does not accepts any body attribute

There is a example as well which shows that you need to pass body in write method

const postData = JSON.stringify({
      requestType: 'createService'
    });

const options = var options = {
    host: 'hostname',
    port: 80,
    path: '/service',
    method: 'POST',
    headers: {
      'Accept': 'application/json',
      'Content-Type': 'application/json',
      'Authorization': "Basic " + new Buffer(username + ":" + pass).toString("base64")
    }
  };

const req = http.request(options, (res) => {
  console.log(`STATUS: ${res.statusCode}`);
  console.log(`HEADERS: ${JSON.stringify(res.headers)}`);
  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();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM