vue本地调用本地后台接口包跨域问题:
Access to XMLHttpRequest at 'http://localhost:8001/users' from origin 'http://localhost:8080' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
cors 跨域资源共享, 在不同服务器、端口之间进行资源访问时,会报该错误。上面的例子就是 8001端口调永8080端口的接口报错。
解决:
方法1、@CrossOrigin
在需要解决的controller方法前使用该注解
@ApiOperation(value = "用户登录")
@ApiResponses(
{@ApiResponse(code=200,message="成功",response = DynamicResponse.class)}
)
@PostMapping
@CrossOrigin
@ResponseBody
public DynamicResponse<User> login (@RequestBody LoginRequest loginRequest){
// ...
}
方法2、配置过滤器 CorsConfig
package com.lile.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 {
private CorsConfiguration buildConfig() {
CorsConfiguration corsConfiguration = new CorsConfiguration();
corsConfiguration.addAllowedOrigin("*");
corsConfiguration.addAllowedHeader("*");
corsConfiguration.addAllowedMethod("*");
return corsConfiguration;
}
@Bean
public CorsFilter corsFilter() {
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
// 配置所有请求
source.registerCorsConfiguration("/**", buildConfig());
return new CorsFilter(source);
}
}