I am using Gin-gonic to create an API. All requests whether thats a GET or a POST will be in JSON.
I have an API call which works fine but I have to add these headers through with the cURL -H "Accept: application/json" -H "Content-type: application/json"
otherwise the POST does not work as expected.
I tried adding this function as middleware but although it changed the headers slightly it still does not work as expected
func CORSMiddleware() gin.HandlerFunc {
return func(c *gin.Context) {
c.Writer.Header().Set("Content-Type", "application/json")
c.Writer.Header().Set("Access-Control-Allow-Origin", "*")
c.Writer.Header().Set("Access-Control-Allow-Headers", "Content-Type, Content-Length, Accept-Encoding, X-CSRF-Token, Authorization")
}
}
Headers when it works (with added header in cURL):
Accept: application/json
Content-type: application/json
Header when it doesn't work (no header in cURL): Accept: */*
Content-Type: application/x-www-form-urlencoded
Is there any way to force the headers rather than asking the user to supply them?
Content-type
is a import HTTP header letting server decide how to parse the HTTP body.Is there any way to force the headers rather than asking the user to supply them?
Hard to say Yes or No, it is depends on your 'user'. For curl, it can not guess the HTTP body format and set Content-Type to 'applicatoin/json' automatically, so you need specify Content-Type. For others like jQuery, programmer can set the
dataType
in postjQuery.post( url [, data ] [, success ] [, dataType ] )
link