用node配置反向代理(解决跨域)、history模式、多入口

const express = require('express');
const app = express();

/* 代理配置 start */
const { createProxyMiddleware } = require('http-proxy-middleware');
const proxyOptions = {
    target: 'http://47.100.240.196:8082', //后端服务器地址
    changeOrigin: true //处理跨域
};
const exampleProxy = createProxyMiddleware(proxyOptions); //api前缀的请求都走代理
app.use('/api',exampleProxy);
/* 代理配置 end */

const history = require('connect-history-api-fallback');
app.use(history({
  htmlAcceptHeaders: ['text/html', 'application/xhtml+xml'],
  index: '/index.html',
  rewrites: [
      { from: 'index', to: '/index.html'}, // 默认入口
      { from: //home/, to: '/home.html'}, // 其他入口
      { from: /^/home/.*$/, to: '/home.html'},
  ]
}));

app.use(express.static('./project'));

app.listen(8087);

  另一套

const fs = require('fs');
const morgan = require('morgan')
const path = require('path')
const express = require('express');
const proxyMiddleWare = require("http-proxy-middleware");
const app = express();
const history = require('connect-history-api-fallback');

const localUrl = path.resolve(__dirname, './porject')

//需要访问的文件的存放目录


// const server = http.createServer(function (req, res) {
//     const url = req.url === '/' ?  '/index.html' : req.url;
//     //客户端输入的url,例如如果输入localhost:8888/index.html
//     //那么这里的url == /index.html 
//     const file = localUrl + url;
//     console.log('地址2'+url);
//     console.log('地址'+file);
//     //E:/PhpProject/html5/websocket/www/index.html 
//     fs.readFile(file, function (err, data) {
//         /*
//         一参为文件路径
//         二参为回调函数
//         回调函数的一参为读取错误返回的信息,返回空就没有错误
//         二参为读取成功返回的文本内容
//         */
//         if (err) {
//             res.writeHeader(404, {
//                 'content-type': 'text/html;charset="utf-8"'
//             });
//             res.write('<h1>404错误</h1><p>你要找的页面不存在</p>');
//             res.end();
//         } else {
//             res.write(data);//将index.html显示在客户端
//             res.end();
//         }


//     });
// }).listen(8888);

// app.get('/home', function(req, res) {
//     console.log(req.url)
//     // res.send('hello world');
//     fs.readFile('./porject/home.html', function (err, data) {
//     /*
//     一参为文件路径
//     二参为回调函数
//     回调函数的一参为读取错误返回的信息,返回空就没有错误
//     二参为读取成功返回的文本内容
//     */
//         if (err) {
//             res.writeHeader(404, {
//                 'content-type': 'text/html;charset="utf-8"'
//             });
//             res.write('<h1>404错误</h1><p>你要找的页面不存在</p>');
//             res.end();
//         } else {
//             res.write(data);//将index.html显示在客户端
//             res.end();
//         }
//     });
// });

const TimeDate = new Date()

const logsDate = `${TimeDate.getFullYear()}-${TimeDate.getMonth()+1}-${TimeDate.getDate()}`


const proxyPath = 'http://47.100.240.196:8082'

const proxyOption ={target:proxyPath,changeOrigoin:true};

app.use("/api",proxyMiddleWare(proxyOption))

app.use(morgan('short',  {stream: fs.createWriteStream(path.join('./logs', `${logsDate}-logs`), {flags: 'a'})}))

app.use(history({
    htmlAcceptHeaders: ['text/html', 'application/xhtml+xml'],
    index: '/index.html',
    rewrites: [
        { from: 'index', to: '/index.html'}, // 默认入口
        { from: //home/, to: '/home.html'}, // 其他入口
        { from: /^/home/.*$/, to: '/home.html'},
//        { from: //.well-known/pki-validation/fileauth/, to: '/.well-known/pki-validation/fileauth.txt'}, // 其他入口
//        { from: /^/.well-known/pki-validation/fileauth/.*$/, to: '/.well-known/pki-validation/fileauth.txt'},
    ]
}));


app.use(express.static('./project'));


app.listen(8087);
console.log('服务器开启成功');
console.log('项目目录为:' + localUrl)
console.log('访问地址:')
// console.log('http://' + getIPAdress() + ':8888/index.html')

  

原文地址:https://www.cnblogs.com/miaSlady/p/12876539.html