AWS Api Gateway需要在接收fetch的OPTIONS请求前收到带有CORS头的请求。因此,需要在发出OPTIONS请求之前发送带有CORS头的请求。
以下是示例代码:
fetch(URL, {
method: 'GET',
mode: 'cors',
headers: {
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Credentials': true,
'Access-Control-Allow-Methods': 'GET, POST, PUT, DELETE, OPTIONS',
'Access-Control-Allow-Headers': 'Authorization, Content-Type'
}
})
.then(response => {
// handle response
})
.catch(error => {
// handle error
});
这里通过在fetch请求中设置mode: 'cors',以便将CORS头包含在发送的请求中。这样,当AWS Api Gateway收到fetch的OPTIONS请求时,它已经收到具有CORS头的请求,并可以正确响应。