api上的jquery ajax请求时出现CORS错误 [英] CORS error when jquery ajax request on api

查看:241
本文介绍了api上的jquery ajax请求时出现CORS错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am using jQuery ajax to send request to some API. Due to the CORS policy I got a CORS error on the browser's console

代码如下

$.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);
    });

错误

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

'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://www.mywebsite.com' is therefore not allowed access.

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

I tried to solve this problem by installing a chrome extension to enable allow cross origin request. This extension somehow solved my problem and got a response from the api. But installing an extension is not good.

我也尝试使用 JSONP(dataType:'jsonp') 发出请求,但是 api 给出的响应不是 json 格式,它是字符串,所以它给出了错误.

I also tried to make the request with JSONP(dataType:'jsonp') but the response given by the api is not in json format, it is string so it gives an error.

JSONP 代码

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

        console.log(result);

    }).error(function (err) {
        //console.log(err);
    });

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

Uncaught ReferenceError: E0002 is not defined where "E0002" is the response string from the api

!!!请帮助!!!

推荐答案

有2种情况-

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

  1. If you have control over the api code then

在标题中进行更改并添加您的来源.

make changes in header and add your origin as well.

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

If you don't have control to change CORS header that is coming from the api

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

you have only one option create a backend code(your own api) in any language you prefer that make an http request and get the data. now use your own api to get data on your frontend.

这篇关于api上的jquery ajax请求时出现CORS错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆