【问题标题】:Why does using axios to fetch data from XML throw cors error? [duplicate]为什么使用 axios 从 XML 中获取数据会引发 cors 错误? [复制]
【发布时间】:2021-12-20 04:45:15
【问题描述】:

我正在使用 axios 从 API 中获取一些包含 XML 数据的数据。我的 API 调用在 Postman 中工作,但在 reactjs 中,它会抛出类似 No 'Access-Control-Allow-Origin' header is present on the requested resource. 我试图把 'Access-Control -Allow-Credentials':true 到标题。但它不起作用。也看看我的代码


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

【问题讨论】:

标签: javascript reactjs xml axios


【解决方案1】:

您的代码抛出错误,因为您的域未在他们的网站上列入白名单,这意味着您不能只查询他们的 URL 并使用它,然后您的浏览器会将其视为安全违规。 https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS

虽然 CORS 只是一个浏览器的东西,你仍然可以自己查询那个 API,然后从你的客户端调用你自己的服务器 API,只要是你的服务器调用他们的 API,然后将数据传递给你的客户。

【讨论】:

  • 所以我需要在nodejs中创建自己的服务器,然后调用API?
  • 是的,然后你调用你自己的 API,反过来调用他们的服务器 API。
猜你喜欢
  • 2021-07-02
  • 2020-05-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-02-21
  • 2021-05-10
相关资源
最近更新 更多