目标问题:vue-cil和express前后端分离的跨域问题。
什么是跨域:同源策略对浏览器的请求行为的限制。
解决方案:
- 修改浏览器设置
- jsonp
- cors
前俩者不合适,最后一个主流正解。
前端使用代理
vue.config,js
module.exports = { outputDir:"../generatorApp/pub", // devServer: { // proxy: { // '/api': { // target: 'http://localhost:3000', //本地服务器地址开放的是3000端口 // changeOrigin: true, //這裡true表示实现跨域 // pathRewrite: { // '^/api': '' // } // } // } // } }
后端配置header
app对象上使用中间件:
var allowCrossDomain = function(req, res, next) { res.header('Access-Control-Allow-Origin', 'http://localhost:63342'); res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE'); res.header('Access-Control-Allow-Headers', 'Content-Type'); res.header('Access-Control-Allow-Credentials','true'); next(); }; app.use(allowCrossDomain);