在API上执行jquery ajax请求时发生CORS错误 [英] CORS error when jquery ajax request on api

查看:108
本文介绍了在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'标头出现在所请求的资源上.因此,不允许访问来源" 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);
    });

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

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

!!!请帮助!!!

!!!PLEASE HELP!!!

推荐答案

有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天全站免登陆