【问题标题】:Access Control Allow Origin header not present with fetch api call访问控制允许 Origin 标头不存在于 fetch api 调用中
【发布时间】:2015-12-19 18:11:34
【问题描述】:

所以我正在尝试使用 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)    

结合以下两个建议 - 但错误是相同的。

【问题讨论】:

  • 在您的 jQuery 示例中,您正在调用 localhost:81000,而在您的 fetch 示例中,您正在调用 localhost:8100。这是问题中的拼写错误,还是您要查找的错误?
  • 这是一个错字 - 抱歉 - 正在更改
  • 我不知道你的服务器是什么语言,但你打电话给w.WriteHeader 之前设置`Access-Control-Allow-Origin?
  • 语言是golang, err - 我是w.WriteHeader(http.StatusOK)
  • 如果您重新排列它们以在WriteHeader 之前设置标题,它可能会起作用。实际上,您在写入套接字后在对象上设置标头,因此标头不会被发送。

标签: ajax go same-origin-policy


【解决方案1】:

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

【讨论】:

    【解决方案2】:

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

    幸运的是,有一个解决方法。如果您查看处理此问题的gin-cors 代码,它所做的是重新发送浏览器发送的"origin" 标头。所以要让* 工作,你必须这样做:

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

    【讨论】:

    • 这改变了错误,我现在有一个 net::ERR_SSL_PROTOCOL_ERROR - 为什么会这样?
    • 好的,我尝试了新版本,现在得到了之前的错误。
    • 可以不用https试试吗? SSL 错误与 CORS 问题无关。
    • 我做到了。但我又回到了“Fetch API 无法加载 localhost:8100/districts。请求的资源上没有 'Access-Control-Allow-Origin' 标头。因此不允许访问 Origin 'localhost:8200'。”执行 r.Header.Get('origin') 后出错
    • 之前需要添加标题吗?如果该标头不存在。
    猜你喜欢
    • 2018-02-26
    • 2019-07-09
    • 2018-03-27
    • 1970-01-01
    • 2016-08-21
    • 1970-01-01
    • 2022-06-25
    • 1970-01-01
    • 2020-09-25
    相关资源
    最近更新 更多