Angular-SpringBoot-CORS(未知URL):0未知错误

时间:2018-12-18 14:31:56

标签: angular spring-boot cors

我有一个非常简单的Angular 6服务,它调用了Spring Boot服务。 这是Angular中的样子:

getData(user, numberOfRequests, graphDepth, max): Observable<String> {
    var headers = new Headers();
    var body = {    "user" : user,
                    "numberofRequests" : numberOfRequests,
                    "graphDepth" : graphDepth,
                    "max" : max };
    headers.append('Content-Type', 'application/x-www-form-urlencoded');    
    return this.http.post<String>('http://XX.XX.XXX.XXX:8083/collect', body, httpOptions);
}

这是服务器端:

@CrossOrigin(origins = "*")
    @RequestMapping(value = "/collect", method = RequestMethod.POST, produces = "application/json; charset=UTF-8")
    @ResponseBody
    public String startServices(@RequestBody UserParameters parameters) {
        LOGGER.info("Calling for data");
        String jsonOutput = collect.getData(parameters);
        LOGGER.info("Data ready to be served");
        return jsonOutput;
    }

当两个应用程序都在本地运行或在两个不同的VM上运行时,它运行良好。但是,当我在云服务上进行部署时,我得到的似乎是CORS错误:

 Reason: CORS request did not succeed

error: error { target: XMLHttpRequest, isTrusted: true, lengthComputable: false, … }
headers: Object { normalizedNames: Map(0), lazyUpdate: null, headers: Map(0) }
 message: "Http failure response for (unknown url): 0 Unknown Error"
 name: "HttpErrorResponse"
 ok: false
 status: 0
 statusText: "Unknown Error"
 url: null

当webapp和后端在同一VM或具有2个不同IP的两个单独的VM中运行时,会发生此错误。

您知道什么可能导致该问题吗? 怎么会是CORS错误? 而且您知道如何尝试修复它吗?

谢谢!

1 个答案:

答案 0 :(得分:1)

尝试:

httpOptions = {
    headers : new HttpHeaders({'Content-Type', 'application/x-www-form-urlencoded'})
};

return this.http.post<String>('http://XX.XX.XXX.XXX:8083/collect', body, httpOptions);

如何将标头链接到httpOptions?

对我有用的