nodejs post请求

const http = require('http');
const querystring = require('querystring');

const postData = querystring.stringify({
  'msg': 'Hello World! ----- 哈利路亚'
});

const options = {
  hostname: '192.168.1.6',
  port: 8080,
  path: '/hello',
  method: 'POST',
  headers: {
    'Content-Type': 'application/x-www-form-urlencoded',
    'Content-Length': Buffer.byteLength(postData)
  }
};

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

 

posted @ 2017-05-11 18:01  次序  阅读(437)  评论(0编辑  收藏  举报