英文:
Error when adding vue http header
问题
我有一个使用vuejs
作为前端和go
作为后端的工作应用程序。我正在添加最后的身份验证功能时遇到错误。
当我尝试向vuejs
请求添加任何HTTP头时,我会收到一个错误。
这是我在vue组件
中添加的内容:
http: {
headers: {
Authorization: 'Bearer 123'
}
}
然后我收到一个preflight
错误:
XMLHttpRequest无法加载http://localhost:8000/api/investments?limit=6。响应预检请求未通过访问控制检查:所请求的资源上没有'Access-Control-Allow-Origin'头。因此,不允许访问来源'http://localhost:8080'。
现在我知道这通常是服务器端的问题,但我已经添加了响应头`resp.Header().Set("Access-Control-Allow-Origin", "*")`。`cors`。如果我移除`vue对象`中的http属性,一切都正常工作。这非常奇怪,我甚至尝试使用`go`处理`OPTIONS`请求,但我的API处理程序甚至没有被调用到。
<details>
<summary>英文:</summary>
I have a working application with a front end in `vuejs` and a backend in `go`. I'm in the process of adding the final features to the authentication and I'm running into an error.
When I try to add any http header to the `vuejs` request I get an error.
This is what I'm adding to the `vue component`:
http: {
headers: {
Authorization: 'Bearer 123'
}
}
And I'm getting a `preflight` error:
XMLHttpRequest cannot load http://localhost:8000/api/investments?limit=6. Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:8080' is therefore not allowed access.
Now I know this is usually a server side problem but I am adding the response header `resp.Header().Set("Access-Control-Allow-Origin", "*")`. `cors`. If I remove the the http property in the `vue object` everything works fine. Its pretty bizzare I even tried handling the `OPTIONS` request with `go` but my handler for the api doesn't even get hit.
</details>
# 答案1
**得分**: 0
好的,以下是翻译好的内容:
好的,我找到答案了,这是一个服务器问题,`Authorization`头部没有被授权。所以只需将其作为中间件添加以允许它。
```go
c := cors.New(cors.Options{
AllowedHeaders: []string{"Origin", "Accept", "Content-Type", "Authorization"},
})
handler := c.Handler(router)
log.Fatal(http.ListenAndServe(":8000", handler))
我正在使用rs/cors
包。
英文:
Ok so I found the answer it is a server problem the Authorization
header was not authorized. So just add it as a middleware to allow for it.
c := cors.New(cors.Options{
AllowedHeaders: []string{"Origin", "Accept", "Content-Type", "Authorization"},
})
handler := c.Handler(router)
log.Fatal(http.ListenAndServe(":8000", handler))
I am using the rs/cors
package
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论