HTTP头部未传递到我的API。

huangapple go评论89阅读模式
英文:

Headers http are not delivered to my API

问题

我正在使用Go开发一个API restful,并且在Angular中开发我的前端(不是AngularJS)。但是当我从Angular的Web应用程序中调用我的API时,我在后端看不到我的头部信息,特别是授权头部信息,因为我的API是基于JWT的身份验证。

另外,我想提一下,我正在使用Postman和Go Request客户端来测试我的应用程序,我的头部信息可以正常传递到API。

以下是我的后端的CORS设置和前端的API调用。

我的后端代码:

func Cors() gin.HandlerFunc {
    log.Println("CORS Middleware")
    return func(c *gin.Context) {
        c.Writer.Header().Add("Access-Control-Allow-Origin", "*")
        c.Next()
    }
}

我的前端代码:

getData() {
    const auth = `Bearer ${this.token}`;

    const headers = new Headers({
        'Access-Control-Allow-Origin': '*',
        'Accept': 'application/json',
        'Authorization': auth,
    });

    const options = new RequestOptions(headers);

    console.log(headers); // 这里我可以看到头部信息

    const products = this.http.get('localhost:8000/api/products', options)
                    .subscribe((response: Response) => {
                        this.data = response.json();
                    });
    return products;
}

谢谢,对于我的英语表示抱歉,我认为我的CORS设置可能会引起问题。

英文:

I am developing an API restful in Go and my frontend in Angular (no AngularJS), but when I call my API from my Web App in Angular I do not see my headers in my backend, in special case my authorization header, because my API has authentication based in JWT.

Also I want to mention that I am using Postman and Go Request client to test my app and my headers are delivered in my API without problems.

Attached below is the CORS of my backend and the API call from my frontend.

My backend:

func Cors() gin.HandlerFunc {
	log.Println("CORS Middleware")
	return func(c *gin.Context) {
		c.Writer.Header().Add("Access-Control-Allow-Origin", "*")
		c.Next()
	}
}

My Frontend:

getData() {

const auth = `Bearer ${this.token}`;

const headers = new Headers({
  'Access-Control-Allow-Origin': '*',
  'Accept': 'application/json',
  'Authorization': auth,
});

const options = new RequestOptions(headers);

console.log(headers); //Here I can see 

const products = this.http.get('localhost:8000/api/products', options )
                .subscribe((response: Response) => {
                  this.data = response.json();
                });
return products;
}

Thanks and sorry for my english, I think that my CORS causes problems.

答案1

得分: 0

替换为:

const options = new RequestOptions({ headers: headers });

RequestOptions的构造函数需要一个RequestOptionsArgs,而不是Headers

此外,似乎你对CORS的理解还不够。前端不需要发送任何头信息到后端(当浏览器注意到是CORS请求时,会自动添加所需的头信息)。这些头信息(Access-Control-Allow-Origin)应该由服务器发送。

对于你的后端,这是一个改进的建议(可以处理大多数情况):

func Cors() gin.HandlerFunc {
    log.Println("CORS Middleware")
    return func(c *gin.Context) {
        c.Writer.Header().Set("Access-Control-Allow-Origin", "*")
        c.Writer.Header().Set("Access-Control-Allow-Methods", "POST, GET, OPTIONS, PUT, DELETE, UPDATE")
        c.Writer.Header().Set("Access-Control-Allow-Headers", "Origin, Content-Type, Content-Length, Accept-Encoding, X-CSRF-Token, Authorization")
        c.Writer.Header().Set("Access-Control-Expose-Headers", "Content-Length")
        c.Writer.Header().Set("Access-Control-Allow-Credentials", "true")
        c.Writer.Header().Set("Access-Control-Max-Age", "86400")
        // c.Writer.Header().Set("Content-Type", "application/json") // 如果需要的话取消注释

        if c.Request.Method == "OPTIONS" {
            fmt.Println("OPTIONS")
            c.AbortWithStatus(200)
        } else {
            c.Next()
        }
    }
}
英文:

Instead of

const options = new RequestOptions(headers);

Do:

const options = new RequestOptions({ headers: headers });

The constructor for RequestOptions requires a RequestOptionsArgs, not a Headers.


Also, it seems you are not quite understanding CORS. You don't really need to send any header from the front-end to the back end (the browser will append what you need automatically when it notices it is a CORS request). Those headers (Access-Control-Allow-Origin) should be sent by the server only.

For your back-end, here's an improved suggestion (should handle most cases):

func Cors() gin.HandlerFunc {
    log.Println("CORS Middleware")
    return func(c *gin.Context) {
        c.Writer.Header().Set("Access-Control-Allow-Origin", "*")
        c.Writer.Header().Set("Access-Control-Allow-Methods", "POST, GET, OPTIONS, PUT, DELETE, UPDATE")
        c.Writer.Header().Set("Access-Control-Allow-Headers", "Origin, Content-Type, Content-Length, Accept-Encoding, X-CSRF-Token, Authorization")
        c.Writer.Header().Set("Access-Control-Expose-Headers", "Content-Length")
        c.Writer.Header().Set("Access-Control-Allow-Credentials", "true")
        c.Writer.Header().Set("Access-Control-Max-Age", "86400")
        // c.Writer.Header().Set("Content-Type", "application/json") // uncomment if needed

         if c.Request.Method == "OPTIONS" {
             fmt.Println("OPTIONS")
             c.AbortWithStatus(200)
         } else {
             c.Next()
         }
    }
}

huangapple
  • 本文由 发表于 2017年6月12日 10:22:32
  • 转载请务必保留本文链接:https://go.coder-hub.com/44490565.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定