跨域导致浏览器不保存cookie

5次阅读

共计 1980 个字符,预计需要花费 5 分钟才能阅读完成。

最近做了两个后台的项目, 前后端使用的技术都没有改变, 只是在第一个项目前端配置了代理转发, 第二个项目前端没有配置, 但是就是这一个区别, 使得项目的联调的时候出现问题, 今天就这个问题总结一下

问题

后端使用 cookie 来处理登录验证问题, 登录成功后浏览器有 set-cookie 字段, 但是浏览器没有保存 cookie

原因

在请求的时候, 后端处理了跨域的问题, 例如本机的ip:192.168.1.66 , 发送请求的接口为IP:192.168.1.67, 出现跨域, 后端处理了跨域那么 cookie 只会保存在 67 的地址, 所以不会保存在 66 的就是我们本机的 cookie

处理

前端使用代理转发,vue2.xvue3.x 的版本对于处理代理转发, 有点区别这里也说明一下:

`vue2.x`
// 配置 config 文件下的 index.js

// see http://vuejs-templates.github… for documentation.
const path = require(‘path’)
module.exports = {
dev: {
// Paths
assetsSubDirectory: ‘static’,
assetsPublicPath: ‘/’,
proxyTable: {
‘/v1’: {
target: ‘http://192.168.1.24:8000’,// 请求的地址
changeOrigin: true,
pathRewrite: {
‘^/v1’: ‘/v1’
}
},
onProxyReq: function (proxyReq, req, res) {
// 实在不知道代理后的路径,可以在这里打印出出来看看
console.log(“ 原路径:” + req.originalUrl, “ 代理路径:” + req.path)
}
},
// Various Dev Server settings
host: ‘localhost’, // can be overwritten by process.env.HOST
port: 8080, // can be overwritten by process.env.PORT, if port is in use, a free one will be determined
autoOpenBrowser: false,
errorOverlay: true,
notifyOnErrors: true,
poll: false, // https://webpack.js.org/config…

/**
* Source Maps
*/
// https://webpack.js.org/config…
devtool: ‘cheap-module-eval-source-map’,
// https://vue-loader.vuejs.org/…
cacheBusting: true,
cssSourceMap: true
},

build: {
// Template for index.html
index: path.resolve(__dirname, ‘../dist/index.html’),
// Paths
assetsRoot: path.resolve(__dirname, ‘../dist’),
assetsSubDirectory: ‘static’,
assetsPublicPath: ‘/’,
/**
* Source Maps
*/
productionSourceMap: false,
// https://webpack.js.org/config…
devtool: ‘#source-map’,
// npm install –save-dev compression-webpack-plugin
productionGzip: false,
productionGzipExtensions: [‘js’, ‘css’],
bundleAnalyzerReport: process.env.npm_config_report
}
}

`vue3.x`
// 直接在 vue.config.js 中配置
module.exports = {
// 配置代理
devServer: {
host:”localhost”,// 要设置当前访问的 ip 否则失效
// open: true, // 浏览器自动打开页面
proxy: {
‘/v1’: {
target: ‘http://192.168.1.64:9100/’,
secure: false,
// ws: true,
changeOrigin: true,
pathRewrite:{
‘^/v1′:’/v1’
}
}
}
}
// 关闭 eslint 检测
devServer :{
overlay : {
warnings:false,
errrors:false
}
},
lintOnSave : false,
// 打包问价使用相对路径
publicPath:”,
// 不生成 map 文件
productionSourceMap: false,
}

正文完
 0