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.
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()
}
}
}