前言
最近在跨域、cookie 以及表单上传这几个方面遇到了点小问题,做个简单探究和总结。本文主要介绍了关于axios中cookie跨域及相关配置的相关内容,下面话不多说了,来一起看看详细的介绍吧。
1、 带cookie请求 - 画个重点
axios默认是发送请求的时候不会带上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,以及定位出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)})
上面是我整理给大家的,希望今后会对大家有帮助。
相关文章:
在vue2中通过keep-alive如何使用
在webpack中有关于jquery插件的环境配置(详细教程)
在bootstrap4 + vue2中如何实现分页查询
以上就是在axios中如何实现cookie跨域的详细内容。
