“使用fetch API调用时,未包含Access-Control-Allow-Origin头部”

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

Access Control Allow Origin header not present with fetch api call

问题

所以我正在尝试使用isomorphic-fetch https://www.npmjs.com/package/isomorphic-fetch

我有一个用Go编写的服务器,返回JSON数据。这是我发起调用的方式 -

  1. export function fetchDistricts(geoState) {
  2. return function (dispatch) {
  3. dispatch(requestDistricts(geoState));
  4. return fetch(`http://localhost:8100/districts/`)
  5. .then(response => {console.log(response);})
  6. .then(json => {
  7. console.log("json");
  8. });
  9. }

我在Chrome控制台中得到以下错误:

  1. Fetch API cannot load http://localhost:8100/districts/. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:8200' is therefore not allowed access.

这很奇怪,因为在我的处理程序中,我正在做这个:

  1. func getDistricts(w http.ResponseWriter, r *http.Request) {
  2. w.Header().Set("Content-Type", "application/jsonp;charset=UTF-8")
  3. w.WriteHeader(http.StatusOK)
  4. w.Header().Set("Access-Control-Allow-Origin", "*")
  5. rows, err := db.Query("SELECT * from districts")
  6. //其他代码在这里

此外,这段代码是可以工作的:

  1. var activitiesDfD = $.ajax({
  2. url: "http://localhost:8100/district/1/activities",
  3. type: "GET",
  4. dataType: "json"
  5. });
  6. $.when(activitiesDfD).then(function(data, textStatus, jqXhr) {

为什么使用fetch API会失败,我该如何解决这个问题?

编辑-

我现在尝试了这个:

  1. func getDistricts(w http.ResponseWriter, r *http.Request) {
  2. w.Header().Set("Content-Type", "application/jsonp;charset=UTF-8")
  3. w.Header().Set("Access-Control-Allow-Origin", r.Header.Get(`origin`))
  4. w.WriteHeader(http.StatusOK)

结合下面的两个建议 - 但错误仍然相同。

英文:

So I'm trying to use isomorphic-fetch https://www.npmjs.com/package/isomorphic-fetch

I have a server written in go that is giving back JSON data. This is how I'm making the call -

  1. export function fetchDistricts(geoState) {
  2. return function (dispatch) {
  3. dispatch(requestDistricts(geoState));
  4. return fetch(`http://localhost:8100/districts/`)
  5. .then(response => {console.log(response);})
  6. .then(json => {
  7. console.log("json");
  8. });
  9. }

I get this error in the chrome console

  1. Fetch API cannot load http://localhost:8100/districts/. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:8200' is therefore not allowed access.

This is weird, because in my handler I am doing this

  1. func getDistricts(w http.ResponseWriter, r *http.Request) {
  2. w.Header().Set("Content-Type", "application/jsonp;charset=UTF-8")
  3. w.WriteHeader(http.StatusOK)
  4. w.Header().Set("Access-Control-Allow-Origin", "*")
  5. rows, err := db.Query("SELECT * from districts")
  6. //other code here

Further, this was working

  1. var activitiesDfD = $.ajax({
  2. url: "http://localhost:8100/district/1/activities",
  3. type: "GET",
  4. dataType: "json"
  5. });
  6. $.when(activitiesDfD).then(function(data, textStatus, jqXhr) {

Why would this fail when using the fetch API and how do I get around this?

Edit-

I've now tried this

  1. func getDistricts(w http.ResponseWriter, r *http.Request) {
  2. w.Header().Set("Content-Type", "application/jsonp;charset=UTF-8")
  3. w.Header().Set("Access-Control-Allow-Origin", r.Header.Get(`origin`))
  4. w.WriteHeader(http.StatusOK)

Incorporating the two suggestions below - but the error is the same.

答案1

得分: 1

几乎所有的网络浏览器都会拒绝使用"*"作为Access-Control-Allow-Origin头部的来源。因此,将"*"作为Access-Control-Allow-Origin头部发送会导致同源策略的违规。

幸运的是,有一个解决方法。如果你查看处理这个问题的gin-cors代码,它实际上是重新发送浏览器发送的"origin"头部。所以要使*起作用,你需要这样做:

  1. w.Header().Set("Access-Control-Allow-Origin", r.Header.Get(`origin`))
英文:

Almost all web browsers reject the origin "*". Therefore sending "*" as the Access-Control-Allow-Origin header results in a same-origin-policy violation.

Fortunately there is a work-around. If you look at the gin-cors code that handles this, what it does instead is to re-send the "origin" header sent by the browser. So to make * work, you'd have to do this:

  1. w.Header().Set("Access-Control-Allow-Origin", r.Header.Get(`origin`))

答案2

得分: 0

我最终使用了这个中间件 https://github.com/rs/cors,并且一切都正常工作了。

英文:

I ended up using this middleware https://github.com/rs/cors, and that got everything working correctly.

huangapple
  • 本文由 发表于 2015年9月23日 00:45:55
  • 转载请务必保留本文链接:https://go.coder-hub.com/32722409.html
匿名

发表评论

匿名网友

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

确定