欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

axios携带token跨域请求

程序员文章站 2022-07-10 11:16:57
...

前端在axios中配置请求头

axios.defaults.headers.common['token'] = 'aaa111222';

后端设置支持跨域请求头token字段

response.setHeader("Access-Control-Allow-Origin","*");
response.setHeader("Access-Control-Allow-Methods", "POST,GET,OPTIONS,DELETE,HEAD,PUT,PATCH");
response.setHeader("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept, token");

携带token跨域请求成功的案例:

axios携带token跨域请求

扩展:支持cookie模式

response.setHeader("Access-Control-Allow-Origin","http://www.lihefei.com"); //cookie模式下不能设置为*
response.setHeader("Access-Control-Allow-Methods", "POST,GET,OPTIONS,DELETE,HEAD,PUT,PATCH");
response.setHeader("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept, token");
response.setHeader("Access-Control-Allow-Credentials","true"); //保持前端跨域时携带的cookie