跨域在前端一直是个隐疾,在现代项目框架加持下,跨域变得似乎简单,那么如果是普通项目,如何本地开发代理转发接口实现跨域请求?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | /Users/lijun/Documents/个人项目/Art_Blog ├── Art_Blog.zip ├── README.md ├── babel.config.json ├── dist ├── gulpfile.js ├── gulpfile_V3.js ├── node_modules ├── out.txt ├── package-lock.json ├── package.json ├── server.mjs ├── src └── static |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 | import express from 'express'; import chalk from 'chalk'; import { createProxyMiddleware } from 'http-proxy-middleware'; import { internalIpV4 } from 'internal-ip'; import path from 'path'; // node自带(更多参考https://www.runoob.com/nodejs/nodejs-path-module.html) import { fileURLToPath } from 'url'; // node自带 import connectLivereload from 'connect-livereload'; import livereload from 'livereload'; const __filename = fileURLToPath(import.meta.url); // fileURLToPath函数将文件URL(import.meta.url)解码为路径字符串,并确保在将给定的文件URL转换为路径时正确地附加/调整了URL控制字符(/,%) const __dirname = path.dirname(__filename); // 根据__filename文件的地址返回该文件夹地址"/Users/lijun/Documents/个人项目/Art_Blog" const app = express() const PORT = process.env.PORT || '3000' const staticDir = path.resolve(__dirname, process.env.STATIC_DIR || 'src'); // 路径拼接 // app.use('/', express.static('static')) //设置静态资源路径 app.use(connectLivereload()); app.use(express.static(staticDir)); app.use( '/api', createProxyMiddleware({ target: 'https://www.weipxiu.com/', //代理域名或ip changeOrigin: true, logLevel: 'debug', // node终端可以查看转发过程 pathRewrite: { '^/api': '', }, }) ) app.listen(PORT, async () => { console.log(); console.log(chalk.yellowBright(`server is listening at ${PORT}`)); console.log(); const ip = await internalIpV4(); console.log(chalk.green(`🌏 http://localhost:${PORT}`)); console.log(chalk.green(`🌏 http://127.0.0.1:${PORT}`)); console.log(chalk.green(`🌏 http://${ip}:${PORT}`)); }); const liveReloadServer = livereload.createServer(); liveReloadServer.watch(staticDir); liveReloadServer.server.once('connection', () => { setTimeout(() => { liveReloadServer.refresh('/'); }, 100); }); |
1 2 | // package.json配置执行server.mjs "dev": "cross-env NODE_ENV="development" PORT="3001" STATIC_DIR="static" node server.mjs", |
为实现自动刷新通过connect-livereload、livereload做了进一步配置,其实如果不需要自动刷新功能,本地代理非常简单
上一篇:JS数组中的一个元素的值改变后,数组其它元素值都跟着变了
支付宝扫一扫打赏
微信扫一扫打赏
共 0 条评论关于"前端本地通过Node.js代理解决开发过程中跨域接口转发"
最新评论