NextAuth使用Credentials Provider对接本地Strapi API返回401问题
问题
我正在开发一个NextJS应用并使用NextAuth进行认证。对接线上HTTPS的Strapi API时认证正常,但切换到本地http://localhost:1337的Strapi API时,请求根本无法到达API。不过在另一台设备上相同配置却能正常运行。
仅修改了const apiUrl变量,其余代码保持不变。使用Postman调用http://localhost:1337/api/auth/local接口是可行的,但NextJS应用却无法访问该接口。
signIn函数代码
import axios from 'axios'; //const apiUrl = process.env.REACT_APP_API_URL_LIVE; const apiUrl = process.env.REACT_APP_API_URL_LOCAL; export async function signIn({ email, password }) { const res = await axios.post(`${apiUrl}/auth/local`, { identifier: email, password: password }) return res.data; }
REACT_APP_API_URL_LIVE对应的线上API正常,REACT_APP_API_URL_LOCAL对应的本地API无法工作。
NextAuth配置代码
import { signIn } from "@/services/auth"; import CredentialsProvider from "next-auth/providers/credentials"; export const authOptions = { providers: [ CredentialsProvider({ name: "Credentials", credentials: { email: { label: "Username", type: "text" }, password: { label: "Password", type: "password" }, }, async authorize(credentials, req) { if (credentials == null) { return null; } try { const { user, jwt } = await signIn({ email: credentials.email, password: credentials.password }); return { ...user, jwt }; } catch (error) { return null; } } }), ], callbacks: { session: async({ session, token }) => { session.id = token.id; session.jwt = token.jwt; return Promise.resolve(session); }, jwt: async ({ token, user }) => { const isSignIn = user ? true : false; if (isSignIn) { token.id = user.id; token.jwt = user.jwt; } return Promise.resolve(token); } }, pages: { signIn: '/login' } };
相同配置在另一台电脑上可以正常工作,请问有人遇到过这个问题吗?
可能的解决方案
- 检查环境变量加载情况:Next.js中
REACT_APP_前缀的环境变量需要确保在.env.local文件中配置正确,且项目重启后生效。如果是服务端执行的代码(比如NextAuth的authorize函数),也可以直接使用无前缀的环境变量,确认REACT_APP_API_URL_LOCAL的值确实是http://localhost:1337。 - 调整Strapi的CORS配置:本地Strapi可能未允许Next.js应用的跨域请求。在Strapi的
config/middlewares.js中修改cors中间件配置,添加你的Next.js运行地址(比如http://localhost:3000):
修改后重启Strapi服务。module.exports = [ // 其他中间件 { name: 'strapi::cors', config: { origin: ['http://localhost:3000'], methods: ['GET', 'POST', 'PUT', 'PATCH', 'DELETE', 'OPTIONS'], headers: ['Content-Type', 'Authorization'], }, }, // 其他中间件 ]; - 切换API访问地址形式:NextAuth的
authorize函数在服务端执行,部分系统的localhost可能存在隔离问题。可以尝试将Strapi启动地址改为0.0.0.0,然后用http://127.0.0.1:1337或你的局域网IP作为API地址测试。 - 添加错误日志定位问题:在signIn函数中捕获并打印详细错误信息,确认请求失败的具体原因:
export async function signIn({ email, password }) { try { const res = await axios.post(`${apiUrl}/auth/local`, { identifier: email, password: password }) return res.data; } catch (error) { console.error('登录请求错误详情:', error.response?.data || error.message); throw error; } } - 检查本地网络限制:关闭设备上的防火墙、VPN或代理软件,确认这些工具没有阻止NextJS应用访问本地1337端口。
内容的提问来源于stack exchange,提问作者Gery
相关产品推荐
相关产品推荐

