【问题标题】:"XMLHttpRequest cannot load http://hnify.herokuapp.com/get/top"... No 'Access-Control-Allow-Origin' header is present“XMLHttpRequest 无法加载 http://hnify.herokuapp.com/get/top”... 不存在“Access-Control-Allow-Origin”标头
【发布时间】:2026-01-16 00:00:02
【问题描述】:

我正在使用 REST API(特别是 this Hacker News API),并使用 jQuery 的 .get 方法来检索数据。到目前为止,这是我唯一的代码:

$.get( 'http://hnify.herokuapp.com/get/top', function(data) {
    'use strict';
    console.log(data)
});

这是我面临的错误:

XMLHttpRequest cannot load http://hnify.herokuapp.com/get/top. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:9000' is therefore not allowed access. 

我在 Mac 上使用最新的 Google Chrome。我目前正在通过 localhost 查看它。

我对 REST API 非常非常陌生。提前致谢。

【问题讨论】:

    标签: jquery rest get xmlhttprequest


    【解决方案1】:

    这是因为浏览器不允许来自不同域的请求,在这种情况下,您试图从 localhost 向http://hnify.herokuapp.com/get/top 发出请求。

    您可以使用 JSONP 来处理这种情况并“解决”问题。 http://json-p.org/

    阅读有关 CORS 的更多信息。 http://en.wikipedia.org/wiki/Cross-origin_resource_sharing

    希望对你有帮助。

    【讨论】:

    • 您能详细说明一下 JSONP 吗?具体来说,JSONP 与 jQuery .get 请求的使用?
    最近更新 更多