【问题标题】:How to enable my react frontend to talk to my nextjs backend如何让我的反应前端与我的 nextjs 后端对话
【发布时间】:2021-08-30 17:56:23
【问题描述】:

所以我的设置如下,我有一个在 localhost:3001 上运行的 react 前端和一个在 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 以使用我的设置。

【问题讨论】:

    标签: cors next.js


    【解决方案1】:

    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" },
                ]
              }
            ]
        },
    }
    

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

    【讨论】:

      猜你喜欢
      • 2017-04-17
      • 2021-12-11
      • 2022-11-07
      • 1970-01-01
      • 1970-01-01
      • 2020-06-12
      • 2017-09-28
      • 1970-01-01
      • 2020-03-11
      相关资源
      最近更新 更多