简体   繁体   中英

CORS issue with calling an API using jQuery

I'm trying to call an API which returns XML data in response.

When I run that .htm file on my local machine, it gives me the following error . 从本地机器呼叫

And, when running it from the codepen.io platform, it gives me the following error . 从Codepen平台呼叫

But, when I call the API from Postman or JSON Formatter , it works gives the response. When I simply paste it in the browser and hit Enter, it works there too. But not working with my code. I'm not sure what's the problem. Can anyone please help me?

Here's my code :

<!doctype html>
<html lang="en">

<head>
    <meta charset="utf-8">
    <title>jQuery.parseXML demo</title>
    <script src="https://code.jquery.com/jquery-3.4.1.min.js"></script>
</head>

<body>
    <p id="someElement">Hello</p>
    <p id="anotherElement"></p>

    <script>
        $(document).ready(function () {
            var api_url = 'http://lb.50g.nl/xml/29474bb065f2b30ca5eb3496f231bced.xml'

            $.ajax({
                url: api_url + $(this).text(),
                dataType: "xml",
                async: true,
                method: "GET",
                headers: {
                    "accept": "text/xml",
                    "Access-Control-Allow-Origin": "*"
                },
                crossDomain: true,
                success: function (result) {
                    console.log(result);
                }
            })
        });

    </script>
</body>

</html>

What you are seeing has something to do with what is called CORS.

In essence, you are not allowed to request resources from an other server ( domain ) than the one your document is served from. This is to help mitigate risks of xSite attacks.

The API is working just fine, that is why postman gets you the data, it is actually the browser forbidding the request from been fired from your document.

In order to request resources from a different domain than the one you are serving you have to enforce some security policies.

You can take a look in the answer for more info.

I totally agree with MKougiouris . you are getting the error as a result of Cross-Origin Resource Sharing (CORS) . so your back end reject any API call that is not from the same origin eg server . CORS help you restrict access to some resources from a specified origin. how ever if you are the one that is managing the back-end you can use this code to give access to all origin. header("Access-Control-Allow-Headers", "*") . but this worked for my node project.

app.all('*', function(req, res, next) {
  var origin = req.get('origin'); 
  res.header('Access-Control-Allow-Origin', origin);
  res.header("Access-Control-Allow-Headers", "X-Requested-With");
  res.header('Access-Control-Allow-Headers', 'Content-Type');
  next();
})

Note: if you are working on a confidential project you should restrict access but the above give access to all.

API Gateway from AWS will help you solve this all day long.

When you run an HTTP request it's a good practice to call a module from the back end (with js/node) this will get you around the CORS issue. but why set up a server/back-end when you can use AWS for it.

with a few extra steps you can make an API that passes the request and then call that from your browser where it will send your page a cross domain allowed response.

see my answer here:

How to retrieve cross origin volcanic data in xml?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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