我改了很多地方,至于哪个位置最关键我也不懂,可以都试一下
首先是后台的配置,最为关键的配置
security的配置
我就写最主要的
@EnableWebSecurity
@Configuration
@EnableGlobalMethodSecurity(prePostEnabled = true)
@Order(-1)
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.cors()//我最后是加了这个才好的
}
}
然后是一个配置类 也很重要,配置一般的跨域问题
package com.trueway.zhdwapp.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;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
/**
* @author cai
* @version 1.0
* @date 2020/4/8 21:06
*/
@Configuration//配置解决跨域问题
public class CorsConfig implements WebMvcConfigurer {
private CorsConfiguration buildConfig() {
CorsConfiguration corsConfiguration = new CorsConfiguration();
corsConfiguration.addAllowedOrigin("*");
corsConfiguration.addAllowedHeader("*");
corsConfiguration.addAllowedMethod("*");
corsConfiguration.addExposedHeader("Authorization");
return corsConfiguration;
}
@Bean
public CorsFilter corsFilter() {
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
source.registerCorsConfiguration("/**", buildConfig());
return new CorsFilter(source);
}
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**")
.allowedOrigins("*")
.allowedMethods("GET","HEAD","POST","PUT","DELETE","OPTION")
.allowCredentials(true)
.maxAge(3600)
.allowedHeaders("*");
}
}
之后是前端修改
这边不是传统的axios,要模拟form的传递,好像是security的原因吧
async initWebSocket() {
let self = this
let {status}= await self.$axios({
method: 'post',
url: 'http://192.168.7.42:8081/logins',
data: {
username: '4A078782E75A42FAA9591E9513E35087',
},
transformRequest: [
function (data) {
let ret = ''
for (let it in data) {
ret +=
encodeURIComponent(it) +
'=' +
encodeURIComponent(data[it]) +
'&'
}
return ret
}
],
headers:{
'Content-Type': 'application/x-www-form-urlencoded'
}
})
结束