axios跨域携带Cookie配置指南
前言
近期在处理跨域、Cookie传递以及表单上传等场景时遇到了一些常见障碍,特此进行梳理与总结。本文将重点解析在使用axios发起请求时,如何正确配置以支持跨域环境下的Cookie携带,并附带相关的前后端配置细节供参考。
1、 带cookie请求 - 画个重点
默认情况下,axios在发送HTTP请求时不会自动携带Cookie。若需实现此功能,必须通过配置withCredentials: true参数来解决。与此同时,这一操作要求后端服务器进行相应的配合设置,否则请求将被浏览器拦截。
- header信息
Access-Control-Allow-Credentials:true - 需要注意的是,Access-Control-Allow-Origin响应头不能设置为通配符'*'。这是因为当Access-Control-Allow-Credentials设置为true时,浏览器禁止使用通配符,必须明确配置具体的源地址。
如果后端错误地设置了Access-Control-Allow-Origin: '*' , 会有如下报错信息
Failed to load http://localhost:8090/category/lists: The value of the 'Access-Control-Allow-Origin' header in the response must not be the wildcard '*' when the request's credentials mode is 'include'. Origin 'http://localhost:8081' is therefore not allowed access. The credentials mode of requests initiated by the XMLHttpRequest is controlled by the withCredentials attribute.
后端的上述配置项缺一不可,否则会导致跨域请求失败。以下贴出我的后端配置示例:
const express = require('express')
const app = express()
const cors = require('cors') // 此处我的项目中使用express框架,跨域使用了cors npm插件
app.use(cors{
credentials: true,
origin: 'http://localhost:8081', // web前端服务器地址
// origin: '*' // 这样会出错
})
成功之后,可在请求中看到
2、我的前端项目代码的axios配置
对axios进行统一配置不仅能显著提升开发效率,还能有效避免潜在Bug,并在出现问题时便于快速定位(例如方便捕获error信息)。
建议建立一个单独的fetch.js文件来封装axios请求逻辑,并将其作为模块方法暴露给其他组件调用。
import axios from 'axios'
// 创建axios实例
const service = axios.create({
baseURL: process.env.BASE_API, // node环境的不同,对应不同的baseURL
timeout: 5000, // 请求的超时时间
//设置默认请求头,使post请求发送的是formdata格式数据// axios的header默认的Content-Type好像是'application/json;charset=UTF-8',我的项目都是用json格式传输,如果需要更改的话,可以用这种方式修改
// headers: {
// "Content-Type": "application/x-www-form-urlencoded"
// },
withCredentials: true // 允许携带cookie
})
// 发送请求前处理request的数据
axios.defaults.transformRequest = [function (data) {
let newData = ''
for (let k in data) {
newData += encodeURIComponent(k) + '=' + encodeURIComponent(data[k]) + '&'
}
return newData
}]
// request拦截器
service.interceptors.request.use(
config => {
// 发送请求之前,要做的业务
return config
},
error => {
// 错误处理代码
return Promise.reject(error)
}
)
// response拦截器
service.interceptors.response.use(
response => {
// 数据响应之后,要做的业务
return response
},
error => {
return Promise.reject(error)
}
)
export default service
如下所示,如果需要调用ajax请求
import fetch from '@/utils/fetch'
fetch({
method: 'get',
url: '/users/list'
})
.then(res => {
cosole.log(res)
})
总结
以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作具有一定的参考学习价值,如果有疑问大家可以留言交流,谢谢大家对本站的支持。