首页 > 代码库 > nodejs post请求

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

 

nodejs post请求