我正处于设置 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()
}
我收到一条错误消息
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.
请注意:端点使用 Postman 按预期工作。
我做了一些研究,发现一些资源说我应该调用内部 next.js 端点(pages/api),然后从那里调用我的 api。这是 next.js 的最佳实践吗?在react中我只是用来直接调用api。
除了如何解决这个问题之外,我想知道这种情况下的最佳做法是什么?谢谢。
如果您有单独的前端和后端服务器(例如,next.js 和express),并且无法侦听同一端口,则有两种广泛的替代方案:
浏览器从一台服务器加载前端并向另一台服务器发出 API 请求
next.js <-- browser --> express
这需要后端应用程序设置 CORS 标头,例如使用cors https://www.npmjs.com/package/cors和声明
app.use(cors({origin: "host of next.js", ...}));
或者浏览器向 next.js 的端口发出所有请求,这会将所有 API 请求转发到其他服务器
browser --> next.js --> express
在这种情况下,不需要 CORS,但 API 请求比以前需要更多的跃点。所以这是简单性与性能的比较(就像经常发生的那样)。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)