douxuexiao1748 2015-09-22 16:45
浏览 74
已采纳

访问控制允许源标头不随提取API调用提供

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 -

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");
            });
}

I get this error in the chrome console

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

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

Further, this was working

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

$.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

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)    

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

  • 写回答

2条回答 默认 最新

  • douba8758 2015-09-22 17:14
    关注

    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:

    w.Header().Set("Access-Control-Allow-Origin", r.Header.Get(`origin`))
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 保护模式-系统加载-段寄存器