我正在尝试使用访存向API端点发出get请求。我对如何处理CORS的理解有些脱节。
我在这个问题上花费了大量时间,并且暂时使用了变通方法,但是我想正确地处理此问题,但是我似乎能找到的唯一答案是一个通用答案。 “ CORS标头应在服务器端处理”,没有描述。这是我的代码的基本外观:
//客户端
fetch(`https://example.com/api/zipLookup?ZipCode=${zip}`)
.then(response => response.json())
.then(data => {
//do something
})
.catch(err => console.log(err))
//服务器端
const express = require('express');
const app = express();
const port = 3000;
const cors = require('cors');
app.use(express.static(__dirname + '/../client/dist'));
app.use(cors())
app.get('/https://example.com.com/api/zipLookup?ZipCode=:zip',
function (req, res, next) {
console.log('work')
});
app.listen(port, () => console.log(`listening on port ${port}`));
该请求不会发送到我的服务器app.get,因为console.log没有显示,所以我认为是在不与服务器交互的情况下发出请求的。
这是我得到的错误
Access to fetch at 'https://example.com/api/zipLookup' from origin
'http://127.0.0.1:3000' has been blocked by CORS policy:
No 'Access-Control-Allow-Origin' header is present on the requested resource.
If an opaque response serves your needs, set the request's mode
to 'no-cors' to fetch the resource with CORS disabled.
TypeError: Failed to fetch
Cross-Origin Read Blocking (CORB) blocked cross-origin response
https://example.com/api/zipLookup with MIME type text/HTML.
See https://www.chromestatus.com/feature/5629709824032768 for more details.
我在这里的理解有一些基本的脱节,我一直无法找到解决方案。
感谢您的时间。