Open timshaw9791 opened 3 years ago
后端: cors:添加跨域设置类CorsConfig 代码【 package com.wzvtc.minishop.config;
import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.web.cors.CorsConfiguration; import org.springframework.web.cors.UrlBasedCorsConfigurationSource; import org.springframework.web.filter.CorsFilter;
@Configuration public class CorsConfig { public CorsConfig() { }
@Bean
public CorsFilter corsFilter(){
//1.添加cors配置信息
CorsConfiguration corsConfiguration=new CorsConfiguration();
corsConfiguration.addAllowedOrigin("http://127.0.0.1:8080");
//设置是否发视cookie信息
corsConfiguration.setAllowCredentials(true);
//设置允许请求的发视
corsConfiguration.addAllowedMethod("*");
//设置允许的header
corsConfiguration.addAllowedHeader("*");
//2.为url添加映射路径
UrlBasedCorsConfigurationSource corsSource=new UrlBasedCorsConfigurationSource();
corsSource.registerCorsConfiguration("/**",corsConfiguration);
//3.返回重新定义好的corsSource
return new CorsFilter(corsSource);
}
} 】
配置通过特定的http header token传递sessionid信息(而不是通过cookie):
在pom.xml中添加spring session依赖包:
【
<artifactId>spring-session-jdbc</artifactId>
</dependency>】
session将由spring管理 添加session配置类来将默认从cookie中拿sessionId改为在请求header中拿到 代码【package com.wzvtc.minishop.config;
import org.springframework.context.annotation.Bean; import org.springframework.jdbc.datasource.DataSourceTransactionManager; import org.springframework.session.jdbc.config.annotation.web.http.EnableJdbcHttpSession; import org.springframework.session.web.http.HeaderHttpSessionIdResolver; import org.springframework.transaction.PlatformTransactionManager;
import javax.sql.DataSource;
@EnableJdbcHttpSession public class HttpSessionConfig { @Bean public HeaderHttpSessionIdResolver httpSessionStrategy(){ return new HeaderHttpSessionIdResolver("Authorization"); }
@Bean
public PlatformTransactionManager transactionManager(DataSource dataSource) {
return new DataSourceTransactionManager(dataSource);
}
} 】
springsession 将session存在数据库中,要在数据库中添加相匹配的表: 找到spring-session-jdbc依赖包 在此依赖包中找到和数据库匹配的sql语句,并在数据库中执行sql语句
表建立起来就完成了
另外一个人访问你的微商城页面那么他的后端数据将会被拦截,后端会根据axios里的ip地址识别请求数据的计算机,他请求的IP是前端的IP地址,后端识别不了所以会被拦截
export default {
install: function(vue) {
var auth = vue.prototype.$auth
//创建一个axios
var result = axios.create({
baseURL: 'http://192.168.1.104:8088/'
})
//添加一个请求拦截器去处理添加Authorization
result.interceptors.request.use(config => {
config.headers.Authorization = auth.getAuthorization()
return config
})
vue.prototype.$http = result
}
}
var auth = {
getAuthorization() {
return localStorage.getItem('Authorization');
},
setAuthorization(Authorization) {
localStorage.setItem('Authorization', Authorization);
}
}
在login部分通过this.$auth.setAuthorization(res.data.data.session_id)将获取到的session_id保存到了localStronage,这样在刷新页面时会从本地获取到sessionID,从而解决了刷新后重新登陆的问题
参考大纲: