jquery ajax在api上请求时出现CORS错误

Sel*_*kar 6 javascript api ajax jquery json

我正在使用 jQuery ajax 向某些 API 发送请求。由于 CORS 政策,我在浏览器控制台上收到 CORS 错误

这是通过代码

$.ajax({
        url: sendHere,//api url
        type: 'GET',
        contentType: 'text/plain',
        crossDomain: true,
        beforeSend: function(xhr){
            xhr.withCredentials = true;
        },
    }).done(function (result) {

        console.log(result);

    }).error(function (err) {
        //console.log(err);
    });
Run Code Online (Sandbox Code Playgroud)

错误

请求的资源上存在“Access-Control-Allow-Origin”标头。因此,不允许访问来源“ http://www.mywebsite.com ”。

我尝试通过安装 chrome 扩展以启用允许跨源请求来解决此问题。这个扩展以某种方式解决了我的问题并得到了 api 的响应。但安装扩展并不好。

我还尝试使用 JSONP(dataType:'jsonp') 发出请求,但 api 给出的响应不是 json 格式,它是字符串,因此会出现错误。

使用 JSONP 编写代码

$.ajax({
        url: sendHere,//api url
        type: 'GET',
        crossDomain: true,
        dataType:'jsonp',
    }).done(function (result) {

        console.log(result);

    }).error(function (err) {
        //console.log(err);
    });
Run Code Online (Sandbox Code Playgroud)

未捕获的引用错误:未定义 E0002,其中“E0002”是来自 api 的响应字符串

!!!请帮忙!!!

Rav*_*mar 2

有2种情况——

  1. 如果您可以控制 api 代码,那么

    更改标题并添加您的来源。

  2. 如果您无法控制更改来自 api 的 CORS 标头

    您只有一个选择,使用您喜欢的任何语言创建后端代码(您自己的 api)来发出 http 请求并获取数据。现在使用您自己的 api 来获取前端数据。