添加Vue的HTTP头时出现错误。

huangapple go评论125阅读模式
英文:

Error when adding vue http header

问题

我有一个使用vuejs作为前端和go作为后端的工作应用程序。我正在添加最后的身份验证功能时遇到错误。

当我尝试向vuejs请求添加任何HTTP头时,我会收到一个错误。

这是我在vue组件中添加的内容:

  1. http: {
  2. headers: {
  3. Authorization: 'Bearer 123'
  4. }
  5. }

然后我收到一个preflight错误:

  1. XMLHttpRequest无法加载http://localhost:8000/api/investments?limit=6。响应预检请求未通过访问控制检查:所请求的资源上没有'Access-Control-Allow-Origin'头。因此,不允许访问来源'http://localhost:8080'。
  2. 现在我知道这通常是服务器端的问题,但我已经添加了响应头`resp.Header().Set("Access-Control-Allow-Origin", "*")``cors`。如果我移除`vue对象`中的http属性,一切都正常工作。这非常奇怪,我甚至尝试使用`go`处理`OPTIONS`请求,但我的API处理程序甚至没有被调用到。
  3. <details>
  4. <summary>英文:</summary>
  5. I have a working application with a front end in `vuejs` and a backend in `go`. I&#39;m in the process of adding the final features to the authentication and I&#39;m running into an error.
  6. When I try to add any http header to the `vuejs` request I get an error.
  7. This is what I&#39;m adding to the `vue component`:
  8. http: {
  9. headers: {
  10. Authorization: &#39;Bearer 123&#39;
  11. }
  12. }
  13. And I&#39;m getting a `preflight` error:
  14. XMLHttpRequest cannot load http://localhost:8000/api/investments?limit=6. Response to preflight request doesn&#39;t pass access control check: No &#39;Access-Control-Allow-Origin&#39; header is present on the requested resource. Origin &#39;http://localhost:8080&#39; is therefore not allowed access.
  15. Now I know this is usually a server side problem but I am adding the response header `resp.Header().Set(&quot;Access-Control-Allow-Origin&quot;, &quot;*&quot;)`. `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&#39;t even get hit.
  16. </details>
  17. # 答案1
  18. **得分**: 0
  19. 好的,以下是翻译好的内容:
  20. 好的,我找到答案了,这是一个服务器问题,`Authorization`头部没有被授权。所以只需将其作为中间件添加以允许它。
  21. ```go
  22. c := cors.New(cors.Options{
  23. AllowedHeaders: []string{"Origin", "Accept", "Content-Type", "Authorization"},
  24. })
  25. handler := c.Handler(router)
  26. 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.

  1. c := cors.New(cors.Options{
  2. AllowedHeaders: []string{&quot;Origin&quot;, &quot;Accept&quot;, &quot;Content-Type&quot;, &quot;Authorization&quot;},
  3. })
  4. handler := c.Handler(router)
  5. log.Fatal(http.ListenAndServe(&quot;:8000&quot;, handler))

I am using the rs/cors package

huangapple
  • 本文由 发表于 2015年11月29日 10:56:56
  • 转载请务必保留本文链接:https://go.coder-hub.com/33978918.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定