Vercel Dev - 对预检请求的响应未通过访问控制检查

问题描述 投票:0回答:1

情况是这样的。在本地开发环境中向我的无服务器函数发出 POST 请求时,我收到 CORS 错误。部署到 Vercel 的两个项目之间完全没有问题。这不是一个简单的 POST 请求,因为有一个有效负载。当没有有效负载时,我可以使用简单的 POST 请求,也可以使用 GET 请求。我已按照 Vercel here 详细说明的所有步骤进行操作。我应该提到的是,我的包含无服务器功能的项目没有使用框架,它是 vanilla js。

完整的错误是这样的,“对预检请求的响应未通过访问控制检查:请求的资源上不存在“Access-Control-Allow-Origin”标头。”但这根本不是真的,我正在正确设置标题。这是我的包装函数中的内容:

// I have a local .env file where this variable is set and I can confirm comes through in other serverless functions
const ACCESS_CONTROL_ALLOW_ORIGIN = process.env.ACCESS_CONTROL_ALLOW_ORIGIN;

export const allowCors = (func) => {
    return (req, res) => {
        // For the preflight request, we never actually hit this log statement
        console.log(req.headers.origin);
        res.setHeader('Access-Control-Allow-Credentials', true);
        res.setHeader('Access-Control-Allow-Origin', ACCESS_CONTROL_ALLOW_ORIGIN);
        // I tried this as well to no avail
        // res.setHeader('Access-Control-Allow-Origin', req.headers.origin);
        res.setHeader('Access-Control-Allow-Methods', 'GET,OPTIONS,PATCH,DELETE,POST,PUT')
        res.setHeader(
            'Access-Control-Allow-Headers',
            'X-CSRF-Token, X-Requested-With, Accept, Accept-Version, Content-Length, Content-MD5, Content-Type, Date, X-Api-Version'
        )
        if (req.method === 'OPTIONS') {
            res.status(200).end();
            return;
        }
        return func(req, res);
    };
}

这是无服务器功能:

import { allowCors } from '../src/util';

const login = allowCors((request, response) => {
    return response.status(200).json({
        status: true
    });
});

export default login;

以下是预检请求的标头:

Accept:
*/*
Accept-Encoding:
gzip, deflate, br
Accept-Language:
en-US,en;q=0.9
Access-Control-Request-Headers:
content-type
Access-Control-Request-Method:
POST
Cache-Control:
no-cache
Connection:
keep-alive
Host:
localhost:3000
Origin:
http://localhost:5173
Pragma:
no-cache
Referer:
http://localhost:5173/
Sec-Fetch-Dest:
empty
Sec-Fetch-Mode:
cors
Sec-Fetch-Site:
same-site
User-Agent:
Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/119.0.0.0 Safari/537.36

再次强调,这只是从开发环境发出请求时的问题。在本例中,本地主机:5173 到本地主机:3000。希望这足以引发一些想法。

感谢您的意见!

cors serverless vercel preflight
1个回答
0
投票

我也有这个问题。让我抓狂

© www.soinside.com 2019 - 2024. All rights reserved.