我改了很多地方,至於哪個位置最關鍵我也不懂,可以都試一下
首先是後臺的配置,最爲關鍵的配置
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'
}
})
結束