首页 > 解决方案 > 如何让我的反应前端与我的 nextjs 后端对话

问题描述

所以我的设置如下,我有一个在 localhost:3001 上运行的反应前端和一个在 localhost:3000 上运行的 nextjs 后端。我在 /api/employee 有一个休息端点,我正在尝试使用以下代码从我的前端获取数据:

fetch(process.env.REACT_APP_API_URL + "/employee/")
            .then((response) => {
                if (response.status === 200) {
                    return response.json();
                } else {
                    throw new Error(response.statusText);
                }
            })
            .then(
                (result) => {
                    setLoaded(true)
                    dispatch(addEmployee(result));
                }
            )
            .catch((error) => {
                setLoaded(true)
                setError("It looks like an Error happend when trying to load the data please reloade the Website and if the Problem persists notify the Administrator.")
                setHasError(true)
            })

但是每次我尝试获取数据时,都会出现 cors 错误:

Access to fetch at 'http://localhost:3000/api/employee/' from origin 'http://localhost:3001' 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.

我尝试以多种不同的方式在我的后端启用 cors,但都没有奏效。我尝试手动添加标题:

res.setHeader('Allow', ['GET', 'PUT'])
res.setHeader('Access-Control-Allow-Origin', '*')

我尝试使用 NextCors 包:

await NextCors(req, res, {
        methods: ['GET', 'HEAD', 'PUT', 'PATCH', 'POST', 'DELETE'],
        origin: '*',
        optionsSuccessStatus: 200,
    });

如果没有 cors 配置,我在 extjs 中的文件如下所示:

文件:pages/api/employee

export default async function handler(req, res) {
    // i tried to configure cors here

    if (req.method === 'PUT') {
        const feed = await prisma.employee.create({
            data: req.employee,
        })
        res.status(200).json(feed)
    } else if (req.method === 'GET') {
        const feed = await prisma.employee.findMany({});
        res.status(200).json(feed)
    }
    else {
        res.status(404)
    }
}

所以我的问题是我需要做什么才能正确配置 cors 以使用我的设置。

标签: corsnext.js

解决方案


next.config.js

module.exports = {
    

    //avoiding CORS error, more here: https://vercel.com/support/articles/how-to-enable-cors
    async headers() {
        return [
          {
            // matching all API routes
            source: "/api/:path*",
            headers: [
              { key: "Access-Control-Allow-Credentials", value: "true" },
              { key: "Access-Control-Allow-Origin", value: "*" },
              { key: "Access-Control-Allow-Methods", value: "GET,OPTIONS,PATCH,DELETE,POST,PUT" },
              { key: "Access-Control-Allow-Headers", value: "X-CSRF-Token, X-Requested-With, Accept, Accept-Version, Content-Length, Content-MD5, Content-Type, Date, X-Api-Version" },
            ]
          }
        ]
    },
}

PS 是因为 localhost,CORS 策略比较奇怪


推荐阅读