在 next.js 中调用 API 并避免 CORS 错误的最佳实践

use*_*311 3 node.js cors express reactjs next.js

我正处于设置 next.js 应用程序的早期阶段,到目前为止我只有使用 React 的经验。

我在 localhost:3000 上设置了一个前端应用程序 (next.js),在 localhost:5000 上设置了一个后端应用程序 (node.js/express)。他们都工作。

现在我尝试从前端调用快速端点,我正在做的是:

const registerUser = async event => {
        event.preventDefault()
        
        const res = await fetch(
            process.env.NEXT_PUBLIC_SERVER + '/user/signup',
            {
                body: JSON.stringify({
                    username: event.target.name.value,
                    email: event.target.email.value,
                    password: event.target.password.value
                }),
                headers: {
                    'Content-Type': 'application/json'
                },
                method: 'POST'
            }
        )

        result = await res.json()
    }
Run Code Online (Sandbox Code Playgroud)

我收到一条错误消息

Access to fetch at 'http://localhost:5000/user/signup' from origin 'http://localhost:3000' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: 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.
Run Code Online (Sandbox Code Playgroud)

请注意:端点使用 Postman 按预期工作。

我做了一些研究,发现一些资源说我应该调用内部 next.js 端点(pages/api),然后从那里调用我的 api。这是 next.js 的最佳实践吗?在react中我只是用来直接调用api。

除了如何解决这个问题之外,我想知道这种情况下的最佳做法是什么?谢谢。

Hei*_*ßen 5

如果您有单独的前端和后端服务器(例如,next.js 和express),并且无法侦听同一端口,则有两种广泛的替代方案:

浏览器从一台服务器加载前端并向另一台服务器发出 API 请求

next.js <-- browser --> express
Run Code Online (Sandbox Code Playgroud)

这需要后端应用程序设置CORS标头,例如使用cors和语句

next.js <-- browser --> express
Run Code Online (Sandbox Code Playgroud)

或者浏览器向 next.js 的端口发出所有请求,这会将所有 API 请求转发到其他服务器

browser --> next.js --> express
Run Code Online (Sandbox Code Playgroud)

在这种情况下,不需要 CORS,但 API 请求比以前需要更多的跃点。所以这是简单性与性能的比较(就像经常发生的那样)。