Fetch和Axios带cookie跨域问题

Fetch和Axios带cookie跨域问题

Fetch和Axios请求默认是不带cookie的

PS:感觉cookie使用的越来越少了,用户认证有token方案,本地存储有webStorage方案

Fetch
var myHeaders = new Headers();
fetch(url, {
              method: 'GET',
              headers: myHeaders,
              credentials: "include"  //携带cookie的配置
            })

这个时候服务端确实拿到了cookie,但是数据返回报错

ERROR :Fetch API cannot load http://localhost:8077/sonny/l... 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:8080' is therefore not allowed access.

解决方式:

//  后台设置
response.setHeader("Access-Control-Allow-Credentials","true");

Access-Control-Allow-Credentials 头 工作中与{domxref(“XMLHttpRequest.withCredentials”)}} 或Fetch API中的Request() 构造器中的credentials 选项结合使用。Credentials必须在前后端都被配置(即the Access-Control-Allow-Credentials header 和 XHR 或Fetch request中都要配置)才能使带credentials的CORS请求成功。

Axios

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

前端代码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)
})
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值