前段时间, 做了一下小项目, 项目使用的是传统的 html+CSS+JS, 没有采用现在的主流框架, 并且是前后端分离的项目, 所以面临了一个跨域问题和本地开发服务器 (没有和后端同学在一起), 不要废话, 下面是我用 node 搭建的一个本地服务器
准备条件
node,NPM
搭建项目目录
1553237208(1).jpg
初始化项目
NPM init -y
创建目录 view 和文件 App.JS,view 目录下放我们的项目, App.JS 一会用来启动本地服务和配置本地代理
安装相关依赖, 只需要两个个依赖包, express 是 web 开发框架, http-proxy-middleware 就是我们的代理包
NPM install express http-proxy-middleware -S
编写 App.JS, 示例如下:
- // 导入 express, 路径包, 子进程中的异步进程, 代理, 设置项目根目录
- const express = require('express')
- const path = require('path')
- const {exec} = require("child_process")
- const proxyMiddleWare = require("http-proxy-middleware")
- const root = path.join(__dirname, './view')
- // 生成 express 实例, 配置代理, 启动服务
- const App = express();
- // 配置代理设置项 HOST: 为目标服务器 POST: 为启动服务端口
- const { HOST = 'http://123.56.231.107:8081/', PORT = '8899' } = {}
- const proxyOption ={target:HOST,changeOrigoin:true}
- App.set('port', PORT);
- // 设置根目录为静态资源
- App.use('/', express.static(root))
- // 使用反向代理
- App.use("/api",proxyMiddleWare(proxyOption))
- // 启动服务
- App.listen(App.get('port'), () => {
- let url = `http://localhost:${app.get('port')}`
- // 自动打开默认浏览器
- switch (process.platform) {
- case "darwin":
- exec(`open ${url}`);
- case "win32":
- exec(`start ${url}`);
- default:
- exec(`open ${url}`);
- }
- })
在根文件夹内打开控制台启动项目 node ./App.JS
如果想要手机查看, 打开 cmd 窗口, 输入 ipconfig 查看本机 ip, 然后在手机浏览器输入本机 ip + 端口号, 即可查看, 如果无法访问, 请关闭电脑防火墙.
来源: http://www.jianshu.com/p/3bfabc7f7051