nodejs 2017-10-19 14:30:14

nodejs转发POST请求接口

通过nodejs在本地搭建服务器转发后端接口,来解决跨域问题。

// 引入http模块
let http = require('http');
const hostname = '原请求主机名'';

/**
 *  http转发请求
 * @param req
 * @param res
 */
function proxyRequest(req, res) {
 // 获取post参数
  let params = req.body;
 // 请求路径
  let path = req.path;
 // 请求方法类型
  let method = req.method;
 // 请求参数字符串化
  let postData = JSON.stringify(params);
  let str = '';

  let opt = {
    protocol: 'http:',
    hostname: hostname,
    method: method,
    port: null,
    path: path,
    headers: {
      // POST 请求一定要加这两个参数
      // charset=UTF-8 保证中文字符不乱码
      'Content-Type': 'application/json;charset=UTF-8',// 后台只能接受json数据
      // 'Content-Length': postData.length
      'Content-Length': Buffer.byteLength(postData, 'utf8')
    }
  };

  let hreq = http.request(opt, function (hres) {
    hres.setEncoding('utf-8');
    hres.on('data', function (d) {
      str += d;
    }).on('end', function () {
      res.write(str);
      res.end();
    });
  });
  hreq.on('error', function (e) {
    console.log('Got error: ' + e.message);
  });
  hreq.write(postData);
  hreq.end();
}

module.exports = proxyRequest;

过程中碰到的一些问题

  1. postData , headers.Content-Type转换需根据原请求服务器进行相应转换
    一些服务器可能获取方式为postData = querystring.stringify(postData);
    Content-Type 也需根据服务器设置进行相应的更改

  2. 'Content-Type': 'application/json;charset=UTF-8',
    之前上传发现参数一直为乱码,后显式设置编码方式