跨域问题是前端开发很常见的问题
解决方案有不少种前端
jsonp返回vue
Access-Control-Allow-Origin:'*' (须要注意的是 对于post请求会变成option请求需求后端支持)web
前端添加代理vue-cli
前端添加代理
以vue-cli为例,前端添加代理json
dev: { env: require('./dev.env'), port: 8888, autoOpenBrowser: true, assetsSubDirectory: 'static', assetsPublicPath: '/', proxyTable: { '/api':{ target: 'http://localhost:3000', changeOrigin: true, } }
其中'/api'为接口的前缀,target为后端服务地址后端
前端请求示例api
vm.$http.post('/api/reg', JSON.stringify(info)).then(() => { }, () => { });
反向代理
反向代理能够理解为指定一个服务地址为内部服务器地址。
为何须要反向代理
若是只是做为接口请求,其实前端搭建代理服务器就能够了,可是代理服务器并不能知足全部的平常开发。
好比说单点登陆的实现,需求服务端作302跳转。可是前端文件没有部署到后端服务器时,set-cookie是不能成功种下cookie登陆信息的。
这就须要在后端服务器添加反向代理。
示例以下跨域
const http = require('http'); const httpProxy = require('http-proxy'); const proxy = httpProxy.createProxyServer(); const proxyServer = http.createServer((req, res) => { proxy.web(req, res, { target: 'http://localhost:8888', }); }); proxyServer.listen(8088, () => { console.log('proxy server is running '); });
这样前端开发就能够在8088端口了,固然热加载功能是在前端服务器的8888端口服务器