![](/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.