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条)

报告相同问题?

悬赏问题

  • ¥17 pro*C预编译“闪回查询”报错SCN不能识别
  • ¥15 微信会员卡接入微信支付商户号收款
  • ¥15 如何获取烟草零售终端数据
  • ¥15 数学建模招标中位数问题
  • ¥15 phython路径名过长报错 不知道什么问题
  • ¥15 深度学习中模型转换该怎么实现
  • ¥15 HLs设计手写数字识别程序编译通不过
  • ¥15 Stata外部命令安装问题求帮助!
  • ¥15 从键盘随机输入A-H中的一串字符串,用七段数码管方法进行绘制。提交代码及运行截图。
  • ¥15 TYPCE母转母,插入认方向