基于Node 的http转发demo,项目中请使用express+http-proxy-middleware

var http = require("http");
var data = '';

function getData() {
    const options = {
        host: 'www.baidu.com',
        port: 80,
        path: '/index.html',
        method: 'GET',
        headers: {
            'Content-Type':'text/html',
        }
    };

    const req = http.request(options, (res) => {
        console.log(`状态码: ${res.statusCode}`);
        console.log(`响应头: ${JSON.stringify(res.headers)}`);
        res.setEncoding('utf8');
        res.on('data', (chunk) => {
            data += chunk;
            //console.log(`响应主体: ${chunk}`);
        });
        res.on('end', () => {
            // console.log(data);
            console.log('响应中已无数据');
            // return data
        });
    });

    req.end();
}


//调用
// getData();
// setTimeout(()=>{
//     console.log(data)
// },300)

http.createServer((req, res) => {

    getData();
    // Content Type: text/html
    res.writeHead(200, {
        'Content-Type': 'text/html',
    });
    // 响应文件内容
    setTimeout(() => {
        res.write(data.toString());
        res.end();
    }, 300)


}).listen(80, () => {
    console.log('服务器开启成功')
})

项目中请使用:express+http-proxy-middleware

为什么要使用node代理转发?

我们要实现前后端分离,然后前端不在自己的电脑上安装tomcat,这时候,我们通过用node搭建服务器,然后转发我们的请求。例如:自己本地是localhost:3000,我们需要访问http://www.example.com(当然,开发过程中,这个应该是你们后台的tomcat的地址), 来做ajax的数据交互。

创建项目

1
npm init

安装模块

1
npm install express connect-timeout http-proxy-middleware --save-dev

创建js文件

const express = require('express');
const timeout = require('connect-timeout');
const proxy = require('http-proxy-middleware');
const app = express();
 
// 超时时间
const TIME_OUT = 30 * 1e3;
 
// 设置端口
app.set('port', '80');
 
// 设置超时 返回超时响应
app.use(timeout(TIME_OUT));
app.use((req, res, next) => {
 if (!req.timedout) next();
});
 
 
proxyOption = {
 target: 'http://localhost:8080',
 pathRewrite: {
    '^/api/' : '/' // 重写请求,api/解析为/
  },
  changeOrigoin:true
};
 
// 静态资源路径
app.use('/', express.static('src/page'));
 
// 反向代理
app.use('/api/*', proxy(proxyOption));
 
// 监听端口
app.listen(app.get('port'), () => {
 console.log(`server running @${app.get('port')}`);
});
原文地址:https://www.cnblogs.com/lguow/p/11738146.html