Next.js NextAuth API路由调用Express登录接口返回404问题求助
问题根因
你的authorize方法运行在Next.js服务端的Node.js环境中,请求URL缺少http://协议前缀时,axios会将其识别为相对路径,最终请求地址会被拼接为http://localhost:3000/localhost:8080/api/public/signin,无法匹配到8080端口的Express服务,因此返回404。Postman和浏览器调用时会自动补全协议前缀,所以可以正常请求。
修复方案
给请求URL补全http://前缀即可,修改后的代码如下:
async authorize(credentials) { let user = await axios // 补全http协议前缀 .post("http://localhost:8080/api/public/signin", { ...credentials, }) .then((res) => res.data) .catch((e) => console.log("login failed", e)); if (user && user.name && user.user_type) { return user; } else { throw new Error("Login failed. Please check email and password"); } }
优化建议
建议将接口地址配置到环境变量中,避免本地开发和生产环境切换时手动修改地址:
- 在Next.js项目根目录的
.env.local文件中添加配置:
NEXT_PUBLIC_API_BASE_URL=http://localhost:8080
- 代码中直接读取环境变量使用:
.post(`${process.env.NEXT_PUBLIC_API_BASE_URL}/api/public/signin`, { ...credentials, })
内容的提问来源于stack exchange,提问作者Sachin
相关产品推荐
相关产品推荐

