我正在使用 Reactjs 并通过 javascript 中的 AJAX 使用 API。我们如何解决这个问题?以前用过CORS工具,现在需要开启CORS。
最佳答案
在 React 中有 6 种方法可以做到这一点,
number 1 and 2 and 3 are the best:
1-在服务端配置CORS
像这样手动设置 2 个标题:
resonse_object.header("Access-Control-Allow-Origin", "*");
resonse_object.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
3-config NGINX for proxy_pass 解释 here 。
4-使用 chrom 扩展绕过 Cross-Origin-Policy(仅用于开发,不推荐!)
5-使用下面的 URL 绕过跨源策略(仅用于开发)
"https://cors-anywhere.herokuapp.com/{type_your_url_here}"
6-在您的 package.json
文件中使用 proxy
:(仅用于开发)
如果这是您的 API:http://45.456.200.5:7000/api/profile/
将此部分添加到您的 package.json
文件中:
“代理”:“http://45.456.200.5:7000/”,
然后使用 api 的下一部分提出您的请求:
React.useEffect(() => {
axios
.get('api/profile/')
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});
});
关于javascript - 如何在 react.js 中允许 CORS?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46337471/