2023-12-12- ????nodejs做服務器和服務代理

最近遇到在 windows2008部署前端項目的問題,tomact 和 ng 都不太合適小項目,而且配置比較復雜,使用 node搞個服務器吧
把打包好的靜態(tài)文件放在 dist 文件夾下,目錄如下:
-dist
--assets
-- index.html

服務器 express

const path = require('path');
const express = require('express');
const { createProxyMiddleware } = require('http-proxy-middleware');
const PORT = 3001;

const STATIC = path.resolve(__dirname, 'dist');
const INDEX = path.resolve(STATIC, 'index.html');

const app = express();
// Static content
app.use(express.static(STATIC));


// All GET request handled by INDEX file
app.get('*', function (req, res) {
  res.sendFile(INDEX);
});

// Start server
app.listen(PORT, function () {
  console.log('Server up and running on ', `http://localhost:${PORT}/`);
});

搞好服務器,后端小伙伴 cors 跨域也不會弄,只能自己代理了

代理工具 http-proxy-middleware

const path = require('path');
const express = require('express');
const { createProxyMiddleware } = require('http-proxy-middleware');
const PORT = 3001;

const STATIC = path.resolve(__dirname, 'dist');
const INDEX = path.resolve(STATIC, 'index.html');

const app = express();
// Static content
app.use(express.static(STATIC));
+ app.use(
+ '/userCode', // 請求 localhost:3001/userCode/login ->  
+ createProxyMiddleware({
+    target: 'http://10.1.81.45:9080/pf2/', //'http://10.1.81.45:9080/pf2//userCode/login
+   changeOrigin: true,
+  }),
+);


// All GET request handled by INDEX file
app.get('*', function (req, res) {
  res.sendFile(INDEX);
});

// Start server
app.listen(PORT, function () {
  console.log('Server up and running on ', `http://localhost:${PORT}/`);
});
?著作權歸作者所有,轉載或內容合作請聯系作者
【社區(qū)內容提示】社區(qū)部分內容疑似由AI輔助生成,瀏覽時請結合常識與多方信息審慎甄別。
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發(fā)布,文章內容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關閱讀更多精彩內容

友情鏈接更多精彩內容