尝试进行删除时,Angular会出现Cross-Origin错误,但Postman却没有

时间:2017-06-29 12:37:45

标签: angular rest typescript cross-domain

尝试执行此代码时:

deleteUser(id: number): Promise<void> {
   return this.http.delete(GlobalVariables.REST_API_ADDRESS + '/users/' + id)
    .toPromise()
    .then(() => null);
 }

我收到此错误:

    Failed to load resource: the server responded with a status of 404 (Not Found)

    users:1 XMLHttpRequest cannot load http://localhost:8080/users/1. 
Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' 
header is present on the requested resource. Origin 'http://localhost:4200' is therefore not allowed 
access. 
The response had HTTP status code 404.

但是Postman在没有任何明显问题的情况下成功了。

我可以毫无问题地从Angular中获取GET(我在服务器中将Access-Control-Allow-Origin设置为*)。

1 个答案:

答案 0 :(得分:1)

我解决了这个问题,而我实际上并不是在Angular中,问题出在我的Go后端。

我尝试添加此标题

w.Header().Set("Access-Control-Allow-Origin", "*")
在ResponseWriter上

,但这不起作用。您必须使用此程序包https://github.com/rs/cors并设置此类标题

c := cors.New(cors.Options{
        AllowedOrigins: []string{"*"},
        AllowedMethods: []string{"GET", "POST", "DELETE", "UPDATE"},
    })
    handler := cors.Default().Handler(router)
    handler = c.Handler(handler)
    log.Fatal(http.ListenAndServe(":8080", handler))

它正在开发Postman,因为它不是一个浏览器(呃!​​),它允许没有那个标题的通信。