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

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

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&#39;m in the process of adding the final features to the authentication and I&#39;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&#39;m adding to the `vue component`:

    http: {
      headers: {
        Authorization: &#39;Bearer 123&#39;
      }
    }

And I&#39;m getting a `preflight` error:

    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.

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.  


</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{&quot;Origin&quot;, &quot;Accept&quot;, &quot;Content-Type&quot;, &quot;Authorization&quot;},
	})
handler := c.Handler(router)
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:

确定