前言
最近在跨域、cookie 以及表單上傳這幾個方面遇到了點小問題,做個簡單探究和總結(jié)。本文主要介紹了關(guān)于axios中cookie跨域及相關(guān)配置的相關(guān)內(nèi)容,下面話不多說了,來一起看看詳細的介紹吧。
1、 帶cookie請求 - 畫個重點
axios默認是發(fā)送請求的時候不會帶上cookie的,需要通過設(shè)置withCredentials: true來解決。 這個時候需要注意需要后端配合設(shè)置:
Access-Control-Allow-Credentials:true Access-Control-Allow-Origin不可以為 '*',因為 '*' 會和 Access-Control-Allow-Credentials:true 沖突,需配置指定的地址如果后端設(shè)置 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前端服務(wù)器地址 // origin: '*' // 這樣會出錯 })成功之后,可在請求中看到
2、我的前端項目代碼的axios配置
axios統(tǒng)一配置,會很好的提升效率,避免bug,以及定位出bug所在(方便捕獲到error信息)
建立一個單獨的fetch.js封裝axios請求并作為方法暴露出來
import axios from 'axios'// 創(chuàng)建axios實例const service = axios.create({ baseURL: process.env.BASE_API, // node環(huán)境的不同,對應不同的baseURL timeout: 5000, // 請求的超時時間 //設(shè)置默認請求頭,使post請求發(fā)送的是formdata格式數(shù)據(jù)// axios的header默認的Content-Type好像是'application/json;charset=UTF-8',我的項目都是用json格式傳輸,如果需要更改的話,可以用這種方式修改 // headers: { // "Content-Type": "application/x-www-form-urlencoded" // }, withCredentials: true // 允許攜帶cookie})// 發(fā)送請求前處理request的數(shù)據(jù)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 => { // 發(fā)送請求之前,要做的業(yè)務(wù) return config }, error => { // 錯誤處理代碼 return Promise.reject(error) })// response攔截器service.interceptors.response.use( response => { // 數(shù)據(jù)響應之后,要做的業(yè)務(wù) return response }, error => { return Promise.reject(error) })export default service
新聞熱點
疑難解答
圖片精選