【问题标题】:Angular - SpringBoot - CORS (unknown url): 0 Unknown ErrorAngular - SpringBoot - CORS(未知网址):0未知错误
【发布时间】:2019-05-19 00:03:39
【问题描述】:

我有一个非常简单的 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;
    }

当两个应用程序都在本地运行或在 2 个不同的虚拟机上运行时,它运行良好。但是当我在云服务上部署时,我得到了一些似乎是 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 错误? 你知道我该如何解决吗?

谢谢!

【问题讨论】:

    标签: angular spring-boot cors


    【解决方案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?

    对我来说这行得通。

    【讨论】:

    • 其实我的课上有这个:const httpOptions = { headers: new HttpHeaders({ 'Content-Type': 'application/json', 'Authorization': 'my-auth-token' }) };你的修改带来了同样的问题......
    • 哦,好的。您还可以尝试更多更改:在安全配置类(扩展 WebSecurityConfigurerAdapter)中,在方法 configure(HttSecurity httpSecurity) 中尝试:http.cors().disable();甚至可能是 http.csrf().disable();我希望这会有所帮助
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-11-29
    • 1970-01-01
    • 2018-12-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多