当试图通过React调用第三个paty API时,我得到了以下错误:
CORS策略阻止从“”从“https://superheroapi.com/api/apikey/”访问XMLHttpRequest的“http://localhost:3000”:请求的资源上不存在“访问控制-允许-原产地”标题。
我找到的理想解决方案是使用Express创建一个代理服务器,从那里调用API。因为我在后端开发中没有任何背景,所以我很难让它正常工作。这是我已经取得了多大的进步,但是它仍然显示了错误,并且没有调用API。
这是我的server.js
const express = require("express")
const app = express()
const cors = require("cors")
const { default: axios } = require("axios")
app.use(cors())
app.get("/",() => {
response = await axios.request("https://superheroapi.com/api/apikey")
.then((response)=>{
console.log(response);
}
)
})
app.listen((3001), ()=>{
console.log("express on port 3001");
})这是我的App.js
import './App.css';
import axios from 'axios';
function App() {
const getAPI = {
method: "GET",
url: "https://superheroapi.com/api/apikey/",
}
axios.request(getAPI)
.then((response) => {
console.log(response);
})
.catch((error) => {
console.error(error);
});
return (
<>
<h1>hello world</h1>
</>
);
}
export default App;发布于 2021-09-24 14:32:23
从您的App.js调用快速服务器。
const getAPI = {
method: "GET",
url: "http://localhost:3001/"
}其次,我认为您的快速服务器实现是不正确的。应该是这样的,
app.get("/", async (req, res) => {
const response = await axios.request("https://superheroapi.com/api/apikey");
res.send(response);
});为此,您可以查看ExpressJS文档。
发布于 2021-09-24 14:29:07
https://stackoverflow.com/questions/69316346
复制相似问题