繁体   English   中英

试图通过 jQuery getJSON jsonp 读取远程 URL 但它不起作用

[英]Trying to read remote URL vis jQuery getJSON jsonp but its not working

我正在尝试使用NPPES API

我只需要向它发送这样的链接https://npiregistry.cms.hhs.gov/api/?number=1801965413&version=2.1并在 jQuery 中返回结果。

根据我的研究,因为它的跨域我需要使用jsonp但我无法让它工作。

$.getJSON({
    url: "https://npiregistry.cms.hhs.gov/api/?number=1801965413&version=2.1",
    dataType: "jsonp",
    type: "POST",
    jsonpCallback: 'processJSONPResponse',
    contentType: "application/json; charset=utf-8",
    success: function (result, status, xhr) {
        console.log(result);
    },
    error: function (xhr, status, error) {
        console.log("Result: " + status + " " + error + " " + xhr.status + " " + xhr.statusText)
    }
});

我收到以下错误,这是我认为jsonp旨在避免的错误。

跨域读取阻塞 (CORB) 阻止了跨域响应

结果:parsererror 错误:processJSONPResponse 未被调用 200 成功

有没有办法让它工作或任何其他JS方式?

要使 JSONP 工作,API 必须返回有效响应。 这个 API 没有。

这与 JSONP 围绕 CORS 工作的方式有关(我之前在这里更详细地解释了 CORS)。

为了了解 JSONP 是如何工作的,假设我们在我们网站的某处有以下代码作为<script>标签的某处:

processJSONResponse({"some": "json", "from": "wherever"});

这段代码调用了一个 JS 函数processJSONResponse ,其中一些 JSON 作为唯一参数。 我们也知道 JS 可以来自其他来源,比如<script src="somewhere.com/some.js"></script> ,对吧?

好吧,由于 CORS,我们无法直接从另一个源(在您的情况下是 API 端点)加载一些 JSON,但是正如我们上面探讨的那样,从其他地方加载一些 JavaScript 代码完全没问题。

因此,某些 API 具有 JSONP 模式,其中,它们不是直接返回 JSON,而是返回类型为“text/javascript”的响应,并且响应看起来像我进一步展示的脚本:它包含一个函数调用,API 响应是传递给函数的第一个也是唯一的参数。

假设我们在 example.com/api 有一个支持 JSONP 的 API,一个端点可能看起来像 ` https://example.com/api?jsonp=helloThere " 并且响应看起来像这样:

helloThere({"some":"response"});

您会看到 API 必须通过一些包装实际 API 响应的函数调用来响应。 当 API 具有此选项时,您只需要实现该函数(此处为helloThere ),然后您将在 JavaScript 中获得响应。 jQuery 有一个帮助程序来完成这些繁琐的工作(例如,它需要创建一个<script>标签,并将端点的 URL 作为src属性。

不过,您指定的 API 似乎没有 JSONP 支持。 另一种可能是使用像这样的 CORS 代理。 您必须在某处运行带有此功能的服务器,以便它可以添加 CORS 标头。 然后你可以得到这样的数据:

fetch("https://your-cors-proxy.com/https://npiregistry.cms.hhs.gov/api/?number=1801965413&version=2.1")
.then(response => response.json())
.then(console.log)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM