简体   繁体   English

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

[英]CORS error when jquery ajax request on api

I am using jQuery ajax to send request to some API. 我正在使用jQuery ajax向某些API发送请求。 Due to the CORS policy I got a CORS error on the browser's console 由于CORS策略,我在浏览器控制台上收到了CORS错误

Here's by code 这是代码

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

Error 错误

'Access-Control-Allow-Origin' header is present on the requested resource. 'access-Control-Allow-Origin'标头出现在请求的资源上。 Origin ' http://www.mywebsite.com ' is therefore not allowed access. 因此,不允许来源“ http://www.mywebsite.com ”访问。

I tried to solve this problem by installing a chrome extension to enable allow cross origin request. 我尝试通过安装chrome扩展来解决此问题,以启用允许跨源请求。 This extension somehow solved my problem and got a response from the api. 这个扩展以某种方式解决了我的问题,得到了api的响应。 But installing an extension is not good. 但安装扩展程序并不好。

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(dataType:'jsonp')发出请求,但是api给出的响应不是json格式,它是字符串,所以它给出了一个错误。

Code with JSONP 代码与JSONP

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

        console.log(result);

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

Uncaught ReferenceError: E0002 is not defined where "E0002" is the response string from the api 未捕获的ReferenceError:未定义E0002,其中“E0002”是来自api的响应字符串

!!!PLEASE HELP!!! !!!请帮忙!!!

There are 2 situations - 有两种情况 -

  1. If you have control over the api code then 如果你可以控制api代码那么

    make changes in header and add your origin as well. 在标题中进行更改并添加原点。

  2. If you don't have control to change CORS header that is coming from the api 如果您无法控制更改来自api的CORS标头

    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. 你只有一个选项用你喜欢的任何语言创建一个后端代码(你自己的api)来发出http请求并获取数据。 now use your own api to get data on your frontend. 现在使用您自己的api来获取前端的数据。

The cors error is cross origin request policy maintained by the browser for security. cors错误是浏览器为了安全而维护的跨源请求策略。 To solve your problem either you will have to allow cors request in your server coding or if you do not have access to the server api code you will have to make the api call from your server to api server 要解决您的问题,您必须在服务器编码中允许cors请求,或者如果您无法访问服务器api代码,则必须从服务器向api服务器发出api调用

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

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