node代理解决跨域

时间:2025-02-06 15:17:29
const express = require('express') const iconv = require('iconv-lite'); const port = 8001 const app = express() app.get('/', (req, res) => { res.send('Hello World!') }) const cors = function(req, res, next){ console.log('LOGGED') // get 方法会自动添加,其他方法需要手动添加 res.set({ "Access-Control-Allow-Origin":"*", "Access-Control-Allow-Methods":"*", // 'Content-Type':"text/html;charset=utf-8" }) next() } app.use(cors) // ------------------- 代理获取日历信息 function onProxyReq(proxyReq, req, res) { console.log('onProxyReq',req.method) proxyReq.method = 'GET' console.log('onProxyReq',proxyReq.method) } function onProxyRes(proxyRes, req, res) { console.log('onProxyRes',proxyRes.headers) res.set('Content-Type',"text/html;charset=utf-8") let d = null proxyRes.on('data',data => { // node 不支持 gbk编码 借助iconv转译 // 解码 const t = iconv.decode(data,'GBK') // 编码 const r = iconv.encode(t,'utf8') d +=r }) proxyRes.on('end',()=>{ res.send(d) }) } const httpProxyMiddleware = require('http-proxy-middleware') const proxyConfig = { target: '', changeOrigin: true, pathRewrite: { '^/calendar' : '/', // 重写请求, }, onProxyReq, // 处理请求 selfHandleResponse:true, // 手动处理响应 onProxyRes // 处理响应函数 } const proxy = httpProxyMiddleware.createProxyMiddleware(proxyConfig) app.use('/calendar',proxy) // ('/calendar',(req,res)=>{ // ('Hello Calendar!') // }) app.listen(port,()=>{ console.log(`服务器运行在 localhost:${port}/`) })