访问控制允许来源 header 不存在于获取 api 调用中

Access Control Allow Origin header not present with fetch api call

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

我有一个用 go 编写的服务器正在返回 JSON 数据。这就是我打电话的方式 -

export function fetchDistricts(geoState) {

    return function (dispatch) {
        dispatch(requestDistricts(geoState));


        return fetch(`http://localhost:8100/districts/`)
            .then(response => {console.log(response);})
            .then(json => {
                console.log("json");
            });
}

我在 chrome 控制台中收到此错误

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.

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

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

此外,这很有效

var activitiesDfD =  $.ajax({
    url: "http://localhost:8100/district/1/activities",
    type: "GET",
    dataType: "json"
});

$.when(activitiesDfD).then(function(data, textStatus, jqXhr) {

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

编辑-

我已经试过了

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

结合下面的两个建议 - 但错误是一样的。

几乎所有的网络浏览器都拒绝来源"*"。因此,将 "*" 作为 Access-Control-Allow-Origin header 发送会导致 same-origin-policy 违规。

还好有一个work-around。如果您查看处理此问题的 gin-cors 代码,它所做的是 re-send 浏览器发送的 "origin" header。所以要使 * 工作,你必须这样做:

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

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