由于同时发送OPTION和POST请求会导致429错误,因此需要分别发送这两个请求。代码示例如下:
// 发送OPTION请求
fetch(url, {
method: 'OPTION'
}).then(response => {
// 处理Option请求返回的信息,例如获取允许进行POST请求的Header信息
const allowMethods = response.headers.get('Access-Control-Allow-Methods');
if (allowMethods.includes('POST')) {
// 若允许进行POST请求,则发送POST请求
fetch(url, {
method: 'POST',
body: JSON.stringify(data),
headers: {
'Content-Type': 'application/json'
}
}).then(response => {
// 处理POST请求返回的信息
}).catch(error => {
// 处理POST请求失败的情况
});
} else {
// 若不允许进行POST请求,则给出提示信息
console.log('POST request is not allowed');
}
}).catch(error => {
// 处理OPTION请求失败的情况
});