由於后端需要通過請求取前端中的cookie信息,在本地開發模式中,直接請求接口,后端無法拿到前端cookie數據,
經測試需在 vue-cli 中使用代理,如果使用Nginx做反向代理需同時修改Nginx配置如下:
一、vue-cli配置
首先在vue.config.js中加入代理配置:
devServer: { port: 3000, open: true, overlay: { warnings: false, errors: true }, proxy: { '/': { //代理的請求 target: 'http://x.x.x.x',//代理的目標地址 changOrigin: true, //開啟代理:在本地會創建一個代理服務,然后發送請求的數據,並同時接收請求的數據,這樣客戶端端和服務端進行數據的交互就不會有跨域問題 ws: false,
//關閉ws代理,代理全部請求時開啟時,ws會導致webpack刷新報錯 } } },
二、Nginx配置
這里nginx做反向代理在Nginx.conf中加入以下配置:
add_header Access-Control-Allow-Origin $http_origin; add_header Access-Control-Allow-Headers "Origin, X-Requested-With, Content-Type, Accept, Cookie"; add_header Access-Control-Allow-Methods "GET, POST, OPTIONS"; proxy_set_header X-Real-IP $remote_addr; add_header 'Access-Control-Allow-Credentials' true; proxy_set_header Cookie $http_cookie;