
# 前端跨域
## vue-cli 跨域
一般设置 `vue.config.js` 里的 `devServer.proxy` , 本质是构建一个开发环境下的本地 node 服务器,进行请求转发
## 生产跨域
前后端未分离时,一般不会有跨域问题;在分离布署下,前端服务器一般是使用 `Nginx` 转发请求,少数是在 api 服务器上设置 `Access-Control-Allow-Origin`
## 花式跨域
- postMessage (推荐)
- jsonp
- [其它](https://www.cnblogs.com/lcspring/p/11079754.html)
## 一步一步实现本地 node 代理转发请求
### 1. node 下载与安装
[Node.js 安装配置](https://www.runoob.com/nodejs/nodejs-install-setup.html)
### 2. 安装 Express 框架 方便构建 web 服务
1 npm install express --save 
### 3. 安装 express-http-proxy 代理插件
1 npm install express-http-proxy --save 
### 4. 入口文件 `index.js`
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 var  express = require ('express' );var  app = express ();app.use (express.json ()); const  httpProxy = require ('express-http-proxy' );const  userServiceProxy = httpProxy ('http://api.xxx.com' , {     proxyReqPathResolver : function  (req ) {     return  req.url .replace ('/api' , '' );   }, }); app.get ('/api/*' , (req, res, next ) =>  {   userServiceProxy (req, res, next); }); app.use ('/' , express.static ('public' )); app.get ('*' , function  (req, res ) {   res.send ('404' ); }); var  server = app.listen (8081 , function  (  var  host = server.address ().address ;   var  port = server.address ().port ;   console .log ('应用实例,访问地址为 http://%s:%s' , host, port); }); 
### 5. 测试 HTML 文件 `index.html` (位于/public)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 fetch ('/api/getUserInfo' , {  method : 'GET' ,   headers : new  Headers ({     'Content-Type' : 'application/json' ,   }), })   .then (res  =>text ())   .catch (error  =>     console .error ('- Error:' , error);   })   .then (response  =>     console .log ('- Success:' , response);     document .write (response);   });