I created a REST API using Go and fasthttp
and a frontend using Vue. Everytime I make an API request, I get the error Access to XMLHttpRequest at 'http://localhost:55555/auth/login' from origin 'http://localhost:8080' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource
in my Browser console. The only time I don't get this error, is the /auth/check
route. Also I made an OPTIONS-Request to my backend and got all the CORS Headers. I don't get them if I make a POST or GET request, but I don't know why.
Backend:
webRouter := router.New()
auth := webRouter.Group("/auth")
auth.GET("/check", authCheck)
auth.POST("/login", authLogin)
auth.GET("/logout", authCheck)
err = fasthttp.ListenAndServe(":"+port, func (ctx *fasthttp.RequestCtx) {
ctx.Response.Header.Set("Access-Control-Allow-Origin", "*")
ctx.Response.Header.Set("Access-Control-Allow-Headers", "authorization, content-type, set-cookie, cookie, server")
ctx.Response.Header.Set("Access-Control-Allow-Methods", "POST, GET, OPTIONS")
ctx.Response.Header.Set("Access-Control-Allow-Credentials", "false")
webRouter.Handler(ctx)
})
if err != nil {
panic(err)
}
Frontend request:
axios.create({
baseURL: 'http://localhost:55555'
}).post('/auth/login', {
email: this.email,
password: this.password
}).then(response => {
console.log(response)
}).catch(err => {
console.log(err)
})
I fixed my issue. I read the docs of fasthttp another time and figured out that the ctx.Error()
method clears all headers. Instead I am now setting the response code and error message manually and everything works fine.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.