duanjunao9348 2017-06-12 02:22
浏览 31
已采纳

标头http未传送到我的API

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条回答 默认 最新

  • doushu8260 2017-06-12 02:34
    关注

    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()
             }
        }
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 数学建模,尽量用matlab回答,论文格式
  • ¥15 昨天挂载了一下u盘,然后拔了
  • ¥30 win from 窗口最大最小化,控件放大缩小,闪烁问题
  • ¥20 易康econgnition精度验证
  • ¥15 msix packaging tool打包问题
  • ¥28 微信小程序开发页面布局没问题,真机调试的时候页面布局就乱了
  • ¥15 python的qt5界面
  • ¥15 无线电能传输系统MATLAB仿真问题
  • ¥50 如何用脚本实现输入法的热键设置
  • ¥20 我想使用一些网络协议或者部分协议也行,主要想实现类似于traceroute的一定步长内的路由拓扑功能