CORS与spring-boot和Vue.js不工作



我使用的是SpringBoot 2.5.6.

我试图通过FileController类中的字节数组上传文件:

@PostMapping("/uploadFileViaStream")
public JSONObject uploadFile1(@RequestBody byte[] bytes) {
ByteArrayInputStream inputStream = new ByteArrayInputStream(bytes);
String fileName = genUUID();
String fileId = null;
fileId = fileService.uploadFile("", fileName, inputStream);

Map<String, Object> map = new HashMap<>(1);
map.put("file", fileId);
return ZheliResult.ok(map);
}

FileController类上添加@CrossOrigin(origins="*")

Chrome显示No 'Access-Control-Allow-Origin' header is present on the requested resource.,这是一个CORS问题。

然后我删除@CrossOrigin(origins="*"),并添加一个配置类:

@Configuration
public class MvcConfiguration implements WebMvcConfigurer {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/*")
.allowedOriginPatterns("*")
.allowCredentials(true)
.allowedMethods("GET", "POST", "DELETE", "PUT","PATCH", "HEAD", "OPTIONS")
.maxAge(3600);
}
}

还是不行

然后我删除这个,并转向Nginx配置CORS:

add_header Access-Control-Allow-Origin $http_origin;
add_header Access-Control-Allow-Credentials true;
add_header Access-Control-Allow-Methods *;
add_header Access-Control-Allow-Headers *;

它确实工作,但过了一会儿CORS问题又出现了。

然后在bootstrap.yml:

中配置SpringCloud网关
gateway:
globalcors:
add-to-simple-url-handler-mapping: true
cors-configurations:
'[/**]': 
allowedOrigins: "*" 
allowedHeaders: "*"
allowedMethods: "*"
allowCredentials: true

Chrome显示:

The 'Access-Control-Allow-Origin' header contains multiple values '*, *', but only one is allowed.

如果我改变*int Nginx或网关http://172.20.10.9:8080, Chrome说:

The 'Access-Control-Allow-Origin' header contains multiple values 'http://172.20.10.9:8080, http://172.20.10.9:8080', but only one is allowed.

有谁能帮我吗?

我将简单地添加过滤器请求并允许CORS通过。HIGHEST_PRECEDENCE秩序很重要。不要遗漏!

@Component
@Order(Ordered.HIGHEST_PRECEDENCE)
public class CorsFilter implements Filter {
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain)
throws IOException, ServletException {
HttpServletResponse response = (HttpServletResponse) res;
HttpServletRequest request = (HttpServletRequest) req;
response.setHeader("Access-Control-Allow-Origin", "*");
response.setHeader("Access-Control-Allow-Credentials", "true");
response.setHeader("Access-Control-Allow-Methods",
"DELETE, GET, OPTIONS, POST, PUT");
response.setHeader("Access-Control-Max-Age", "3600");
response.setHeader("Access-Control-Allow-Headers",
"Origin, X-Requested-With, Content-Type, Accept, Key, Authorization");
if ("OPTIONS".equalsIgnoreCase(request.getMethod())) {
response.setStatus(HttpServletResponse.SC_OK);
} else {
chain.doFilter(req, res);
}
}
}

相关内容

  • 没有找到相关文章

最新更新