新项目前端用的vue全家桶,使用axios代替ajax请求后台接口,在调整注册接口的时候,发现在session里取不到验证码,排查后才知道获取验证码和注册两个请求的session不同,sessionid不一样。
现在调整一下vue的配置,修改main.js文件,添加如下两行代码
import axios from 'axios'
axios.defaults.withcredentials=true;
修改后
import vue from 'vue'
import app from './app'
import router from './router'
import elementui from 'element-ui'
import 'element-ui/lib/theme-chalk/index.css';
import axios from 'axios'
// 默认false 会导致后台接收到的同一用户的不同请求sessionid都不同,需要改为true
axios.defaults.withcredentials=true;
vue.config.productiontip = false
vue.use(elementui)
/* eslint-disable no-new */
new vue({
el: '#app',
router,
components: { app },
template: '<app/>'
})
同时后台也需要配合修改,后台用的是spring boot,下面是修改后的结果
@configuration
public class corsconfig {
private corsconfiguration buildconfig() {
corsconfiguration corsconfiguration = new corsconfiguration();
corsconfiguration.setallowcredentials(true);
// 设置setallowcredentials = true后就不能设置为*了,要设置具体的
corsconfiguration.addallowedorigin("http://192.168.0.35:8080");
corsconfiguration.addallowedorigin("http://localhost:8080");
// 允许任何头
corsconfiguration.addallowedheader("*");
// 允许任何方法(post、get等)
corsconfiguration.addallowedmethod("*");
return corsconfiguration;
}
@bean
public corsfilter corsfilter() {
urlbasedcorsconfigurationsource source = new urlbasedcorsconfigurationsource();
// 对接口配置跨域设置
source.registercorsconfiguration("/**", buildconfig());
return new corsfilter(source);
}
}
这是一个允许跨越请求的类
设置
corsconfiguration.setallowcredentials(true);
设置了上行代码后,addallowedorigin设置成*就不允许了
corsconfiguration.addallowedorigin("*")
需要设置成指定的地址
corsconfiguration.addallowedorigin("http://192.168.0.35:8080");
corsconfiguration.addallowedorigin("http://localhost:8080");
这样就ok了!
补充知识:vue axios sessionid 每次请求都不同的原因,及修改方式
今天应项目需要,需要在请求当中加入sessionid的验证,但是发现每一次发送给后台的请求当中,sessionid都是不一样的,那么原因是什么呢?
查阅度娘之后,发现自己封装的axios配置文件当中,缺少了一行:
import axios from 'axios'
axios.defaults.withcredentials = true
这是axios的文档:
// `withcredentials` 表示跨域请求时是否需要使用凭证
withcredentials: false, // 默认的
在我封装的axios请求当中,是没有 withcredentials的配置的, 如果没有配置为true,默认为false则向后台发送的请求当中不携带cookie信息,如此每一次sessionid自然会不同。
而再加入这一行配置之后,再次测试,发现出现新的的问题:
response to preflight request doesn't pass access control check: 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. the credentials mode of requests initiated by the xmlhttprequest is controlled by the withcredentials attribute.
这个时候,就需要后台的同事帮忙了,在后台的跨域请求头配置当中,进行如下两行的配置:
response.setheader("access-control-allow-origin", "*");// 不能是通配符*
而是:

作用是将访问接口才ip注册进去。
第二个配置是:
access-control-allow-credentials: true
若是不设置成这个,也会出错。
而这样前后都设置完毕之后,再次请求,你会发现,还是出错了,那是因为,你需要在修改一个地址
host: 'localhost', // 这里要修改为你本机的ip地址,那少年,你就成功了 port: 8080, // 端口 autoopenbrowser: false,
以上这篇vue使用axios引起的后台session不同操作就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持。
那晚越女说我?