options请求和axios跨域及cookie传递问题

options请求: 检测请求的接口的信息(服务器接受的方法、跨域中测实际请求是否可以被服务器所接受)

什么情况下会发送options预检请求

浏览器将CORS请求分为两类:简单请求、非简单请求

  • 简单请求(不会发送预检请求)与非简单请求(请求之前发送options)的区别

    1. 请求方法:get、post、head

    2. http请求头信息:
      accept
      accept-language、
      content-language、
      content-type、
      last-event-id

    3. content-type:
      application/x-www-form-urlencoded、
      multipart/form-data、
      text/plain

      同时满足以上两个条件时,才是简单请求,否则为非简单请求

axios跨域并获取cookie

axios详细配置文档

核心:
1.axios全局配置中添加 withCredentials: true 跨域并保存cookie
2.在请求拦截器内设置 content-type:application/json

不是很理解第二点 加了之后不是把所有请求都变成非简单请求了吗
但是不加的话就报错了

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
import axios from 'axios'
import { MessageBox, Message } from 'element-ui'
import store from '@/store'

// create an axios instance
axios.defaults.headers.common['X-Requested-With'] = 'XMLHttpRequest' // ! 可能是非必须
const service = axios.create({
baseURL: process.env.VUE_APP_BASE_API, // url = base url + request url
withCredentials: true, // send cookies when cross-domain requests
timeout: 5000 // request timeout
})

// request interceptor 请求拦截
service.interceptors.request.use(
config => {
config.headers = {
'Content-Type': 'application/json' // 注意:设置很关键
}
return config
},
error => {
// do something with request error
console.log(error) // for debug
return Promise.reject(error)
}
)

后端相应的配置:

1
2
3
response.setHeader('Access-Control-Allow-Credentials',true); // 必须加上
response.setHeader('Access-Control-Allow-Origin','http://localhost:9528'); //不能写成 * ,一定要指定地址
response.setHeader('Set-Cookie','token=cowshield'); //传递的数据

问题描述

按理说应该是可以了
但是后台说因为有options预检请求
所以请求会有两次 但是他能获取的是options那次 后面那个请求获取不到
但是options请求又没有能保存传递的数据 导致一些问题

解决方案

我觉得不严谨 但是有效
大概是 写了一个拦截器 对于options请求直接返回true 就可以进入下一个请求了

参考资料

http://www.ruanyifeng.com/blog/2016/04/cors.html
https://blog.csdn.net/qq_25551573/article/details/80690583

扫一扫,分享到微信

微信分享二维码
  • Copyrights © 2019-2026 John Doe
  • Visitors: | Views:

请我喝杯咖啡吧~

支付宝
微信