如何使获取API在不启用浏览器中的COR的情况下工作
我一直在尝试将此代码用于各种版本: (URL指向NASA APOD API)
try {
const rsp = await fetch(url, {
method: 'GET',
mode: 'cors',
headers: {
'Content-Type': 'application/json',
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Methods': 'GET',
},
})
if (rsp.ok) {
console.log(`>>> no problem with call to fetch api:`)
const data = await rsp.json()
return data
}
console.log(`!!! some other problem occurred with call to fetch api:`, rsp)
} catch (err) {
console.log(`!!! problem with call to fetch api:`, err)
}
当我在Chrome中运行代码时。但是,当我在Firefox中运行相同的代码时,我会从API中返回预期数据。
当我在Chrome中安装扩展名以启用CORS时,我会从API中返回预期的数据。
当我使用fetch头 - 'mode'运行代码时:'no -cors',我在chrome中得到以下响应:
我能理解的是要点是因为API在不同的域(IE来自NASA)。 Firefox给出了类似的响应。
因此,我已经达到了可以通过在浏览器中打开COR(通过浏览器扩展程序)来制作Chrome代码的地步。这显然并不令人满意。
我将感谢有关解决Chrome中此问题的任何建议,它确实涉及使用浏览器级别的CORS打开。
最新尝试:
这是NextJS API路由。
这是使用AXIOS调用API路由
这是Axios的错误。
看来代理不起作用,Responseurl
看起来它来自本地主机而不是目标API地址。
有什么想法吗?
I have been trying to get this code to work in various versions:
(the URL points to the NASA APOD API)
try {
const rsp = await fetch(url, {
method: 'GET',
mode: 'cors',
headers: {
'Content-Type': 'application/json',
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Methods': 'GET',
},
})
if (rsp.ok) {
console.log(`>>> no problem with call to fetch api:`)
const data = await rsp.json()
return data
}
console.log(`!!! some other problem occurred with call to fetch api:`, rsp)
} catch (err) {
console.log(`!!! problem with call to fetch api:`, err)
}
I have been getting this error:
when I run the code in Chrome. However, when I run the same code in FireFox, I get the expected data returned from the API.
When I install an extension in Chrome to enable CORS, I get the expected data returned from the API.
When I run the code with the fetch header - 'mode': 'no-cors', I get the following response in Chrome:
which I can understand to a point because the API is on a different domain (i.e. from NASA). FireFox gives a similar response.
So, I have reached the point where I can make the code in Chrome by switching on CORS in the browser (by means of browser extension). This is clearly not satisfactory.
I would appreciate any suggestions on resolving this problem in Chrome that does involve using a browser-level switching on of CORS.
Latest Attempt:
this is the NextJS api route.
this is the function using axios to call the API route
this is error from axios.
It looks like the proxy is not working, the responseUrl
looks like it is coming from local host not the target API address.
Any ideas please?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
从技术上讲,API不属于您,这是无法将其从您的前端调用到该API的方法,不要试图配置您的前端或浏览器,因为它无济于事。
您可以尝试:
The API doesn't belong to you, technically, it's no way to call that API from your frontend to that API, don't try to config your frontend or browser because it doesn't help.
You can try: