如果在 Vue 的本地开发环境中设置 newAxios.defaults.withCredentials = true
无效,可能是由于开发服务器的配置问题。
在开发环境中,Vue CLI 使用的是 webpack-dev-server 作为开发服务器,默认情况下,webpack-dev-server 不会将跨域请求的凭据发送给服务器。
为了在开发环境中使 withCredentials
生效,你可以在 vue.config.js
文件中进行配置。在该文件中,你可以使用 devServer
选项来配置 webpack-dev-server。
// vue.config.js
module.exports = {
devServer: {
proxy: {
'/api': {
target: 'https://api.example.com',
changeOrigin: true,
withCredentials: true
}
}
}
};
在上述示例中,我们使用 proxy
选项来配置代理,将以 /api
开头的请求代理到目标服务器 https://api.example.com
。通过设置 withCredentials: true
,确保在代理请求中携带凭据。
请注意,使用代理配置后,将请求 /api/data
时,实际会被代理到 https://api.example.com/data
,同时携带凭据。
当你在开发环境中使用这样的配置后,设置 newAxios.defaults.withCredentials = true
将会生效。