我的API服务器在端口8090的spring boot应用程序中运行,而在Angular 6中运行的前端应用程序中运行。 一切正常,直到Access-Control-Allow-Origin标头中只有一个IP。
现在,在不同端口(80和7000)上运行的2个不同的字体最终应用程序使用了API。我在Access-Control-Allow-Origin标头中添加了两个IP,它不起作用
根据this,我们可以有多个以逗号分隔的cors起源
详细信息:
Request:
Accept: /
Accept-Encoding: gzip, deflate
Accept-Language: en-IN,en-GB;q=0.9,en-US;q=0.8,en;q=0.7
Access-Control-Request-Headers: content-type,x-auth
Access-Control-Request-Method: GET
Cache-Control: no-cache
Connection: keep-alive
Host: 192.168.1.10:8090
Origin: http://192.168.1.10:7000
Pragma: no-cache
Referer: http://192.168.1.10:7000/user/dashboard
Response:
Access-Control-Allow-Headers: X-Auth,Origin,X-Requested-With,Content-Type,Accept,X-Forwarded-For
Access-Control-Allow-Methods: GET,POST,OPTIONS,PUT,DELETE
Access-Control-Allow-Origin: http://192.168.1.10,http://192.168.1.10:7000
Access-Control-Expose-Headers: X-Auth
Content-Length: 0
Date: Fri, 01 Feb 2019 05:54:29 GMT
Error:
Access to XMLHttpRequest at 'http://192.168.1.10:8090/api/patient/logout' from origin 'http://192.168.1.10:7000' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: The 'Access-Control-Allow-Origin' header contains multiple values 'http://192.168.1.10,http://192.168.1.10:7000', but only one is allowed.
答案 0 :(得分:3)
在大多数情况下,this是可行的,但是当您在应用程序中请求过滤器时,您需要为此编写代码:
String origin = request.getHeader("Origin");
if (StringUtils.isNoneBlank(origin)) {
if (applicationSettings.getAllowedOrigins().contains("*") || applicationSettings.getAllowedOrigins().contains(origin)) {
response.setHeader("Access-Control-Allow-Origin", origin);
}
} else {
response.setHeader("Access-Control-Allow-Origin", "*");
}
答案 1 :(得分:1)
以下内容应该可以在弹簧靴侧允许多个来源:
@Configuration
public class CorsConfig implements WebMvcConfigurer {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**")
.allowedOrigins("http://192.168.1.10:8090","http://192.168.1.10:7000");
}
}