NodeJS Axios 块 CORS

NodeJS Axios Block CORS

我正在尝试在 NodeJS 服务器应用程序中配置 axios 运行 以故意阻止 CORS。正如我正在尝试测试我的设置以确保正确配置了 CORS。

我面临的问题是 axios 忽略了 CORS 规则并执行查询,无论 API 服务器设置如何。 运行 来自浏览器的应用程序正确阻止了 CORS 违规,但是我需要能够自动执行 CORS 测试。

有人可以告诉我如何告诉 axios 在违反 CORS 时出错吗?

await axios.post(url, query, {timeout: 1000 * 15})

我明白了。 axios 不在浏览器中执行 'preflight' OPTIONS 请求时 运行。不过,您可以复制该行为并通过发送您自己的 OPTIONS 请求来执行您自己的 CORS 检查。

async function testCORS(){
    const url = 'example.com'

    try{
        const result = await axios.options(url, {
            timeout: 1000 * 15,
            headers:{
                origin: 'https://mywebsite.com'
            }
        })
        if(result.status === 204){
            return true;
        }
    } catch(error){
        console.error(error.message);
        return false;
    }
}

确保设置 origin header,因为这是检查中使用的。

成功的 CORS 检查返回状态 204,失败返回 404。