![](/img/trans.png)
[英]origin http://localhost:3000 has been blocked by CORS policy: The Access-Control-Allow-Origin In my react App
[英]How to fix CORS error "http://localhost:3000 is not allowed by Access-Control-Allow-Origin" in a react-app?
我確實為快速服務器找到了一種解決方案,但我無法在我的 react-app 中實現相同的方法。
提到這個。 請建議。 (我是 CORS 的初學者)
這是我的 App.js 文件:
import { useEffect, useState } from "react";
import "./App.css";
function App() {
const APP_ID = "--"
const APP_KEY = "--"
const [counter, setCounter] = useState(0);
useEffect(() => {
getRecipes();
}, [])
const getRecipes = async () => {
const response = await fetch(`https://api.edamam.com/search?q=chicken&app_id=${APP_ID}&app_key=${APP_KEY}&from=0&to=3&calories=591-722&health=alcohol-free`);
const data = response.json();
console.log(data);
}
return <div className="App">
<form className="search-form">
<input className="search-bar" type="text" placeholder="Search query here!" />
<button
className="search-button" type="submit">
Search
</button>
</form>
<h1 onClick={() => setCounter(counter + 1)}>{counter}</h1>
</div>;
}
export default App;
對於生產和幾乎所有用例,這需要在服務器上完成(即您正在使用的后端,通常運行 node.js,而不是 react 的前端)。
但是,create-react-app 確實允許您在客戶端設置代理以在開發期間進行測試,盡管不建議這樣做,因為如果您在將代碼推送到生產環境時忘記刪除它,它可能是一個嚴重的安全問題問題。 如果它只是一個學習項目,你可以這樣做:
如果這是您的 API:http: http://123.4.345.53:7000/api/profile/
:7000/api/profile/ 在您的package.json
文件中添加此部分: "proxy": "http://123.4.345.53:7000/"
然后您可以以下:
React.useEffect(() => {
axios
.get('api/profile/')
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});
});
如果您決定使用專用后端,並且它運行 node.js,則可以這樣做:
var app = express();
app.use(function(req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
next();
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.