2

I am using axios to fetch some data from the API that include XML Data. My API call working in Postman but in reactjs, it throws error like No 'Access-Control-Allow-Origin' header is present on the requested resource. I tried to put 'Access-Control-Allow-Credentials':true to headers.But it doesn't work.Take a look at my code also


import axios from "axios";
import React, { useEffect } from "react";
const convert = require("xml-js");

export default function DailyNews() {
  useEffect(() => {
    axios
      .get("https://www.tcmb.gov.tr/kurlar/today.xml")
      .then(function (response) {
        console.log(response); // this will print xml data structure
        const data = JSON.parse(
          convert.xml2json(response.data, { compact: true, spaces: 2 })
        );
        console.log(data);
      })
      .catch(function (error) {
        console.log(error);
      })
      .then(function () {
        // always executed
      });
  }, []);

  return (
    <div>
      <h1>XML CALISMASI</h1>
    </div>
  );
}

sayinmehmet47
  • 490
  • 5
  • 21
  • 1
    The resource you're requesting (i.e., the tcmb server) has to specify origins from which cross-origin requests are allowed. If your origin is not on the allowed list, your _browser_ won't show you the response (this is a client-side security measure). Postman does not implement CORS protection (discussed a bit here: https://stackoverflow.com/questions/36250615/cors-with-postman) – Nick Nov 06 '21 at 14:42
  • 3
    Does this answer your question? [Why does my JavaScript code receive a "No 'Access-Control-Allow-Origin' header is present on the requested resource" error, while Postman does not?](https://stackoverflow.com/questions/20035101/why-does-my-javascript-code-receive-a-no-access-control-allow-origin-header-i) – fsefidabi Nov 06 '21 at 14:42
  • @fsefidabi so is there any other way to use "https://www.tcmb.gov.tr/kurlar/today.xml" data in my reactapp? – sayinmehmet47 Nov 06 '21 at 14:44
  • 1
    Try to set `Access-Control-Allow-Origin` to `*` instead of `true`. – fsefidabi Nov 06 '21 at 14:48
  • @fsefidabi you mean .get("https://www.tcmb.gov.tr/kurlar/today.xml", { headers: { "Access-Control-Allow-Origin": "*", }, }) – sayinmehmet47 Nov 06 '21 at 14:51
  • 1
    Yes. If you search on the 'Access-Control-Allow-Origin' topic on StackOverflow, you will find several issues that may help you. – fsefidabi Nov 06 '21 at 14:53

1 Answers1

1

Your code is throwing an error because your domain is not whitelisted on their site, which means that you can't just query their URL and use it, then your browser will see it as a security violation. https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS

That being said CORS is only a browser thing, you can still query that API yourself and then call your own server API from your client, as long as it's your server making the call to their API and then passing along the data to your client.