axios的cookie跨域以及相关配置

axios的cookie跨域以及相关配置前端

一、 带cookie请求 - 画个重点node

axios默认是发送请求的时候不会带上cookie的,须要经过设置withCredentials: true来解决。 这个时候须要注意须要后端配合设置:ios

  • header信息 Access-Control-Allow-Credentials:true
  • Access-Control-Allow-Origin不能够为 '*',由于 '*' 会和 Access-Control-Allow-Credentials:true 冲突,需配置指定的地址

若是后端设置 Access-Control-Allow-Origin: '*', 会有以下报错信息web

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.ajax

后端配置缺一不可,不然会出错,贴上个人后端示例:express

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: '*' // 这样会出错
        })

成功以后,可在请求中看到npm

二、个人前端项目代码的axios配置json

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)
})
相关文章
相关标签/搜索