【发布时间】: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>
);
}
【问题讨论】:
-
您请求的资源(即 tcmb 服务器)必须指定允许跨域请求的来源。如果您的来源不在允许列表中,您的 浏览器 将不会向您显示响应(这是客户端安全措施)。 Postman 没有实现 CORS 保护(在这里讨论了一下:stackoverflow.com/questions/36250615/cors-with-postman)
-
@fsefidabi 那么有没有其他方法可以在我的 reactapp 中使用“tcmb.gov.tr/kurlar/today.xml”数据?
-
尝试将
Access-Control-Allow-Origin设置为*而不是true。 -
是的。如果您在 StackOverflow 上搜索“Access-Control-Allow-Origin”主题,您会发现几个可能对您有所帮助的问题。
标签: javascript reactjs xml axios