Estoy configurando un flujo de autenticación con JWT con mi backend strapi y un frontend next.js. Probar el backend con cartero funciona como se esperaba. Obtengo un objeto de usuario y un token JWT. Pero llamar a mi backend desde mi frontend da como resultado un código de estado 500: error interno del servidor. Sinceramente, no veo dónde me equivoco y traté de reescribir esas llamadas desde cero una y otra vez. ¿Alguien ve dónde me he equivocado?
Aquí está mi register.js donde ocurre la llamada a mi backend:
import cookie from 'cookie' import { API_URL } from '@/config/index' export default async (req, res) => { if (req.method === 'POST') { const { username, email, password } = req.body const strapiRes = await fetch(`${API_URL}/auth/local/register`, { method: 'POST', headers: { 'Content-Type': 'application/json', }, body: JSON.stringify({ username, email, password, }), }) const data = await strapiRes.json() if (strapiRes.ok) { // Set Cookie res.setHeader( 'Set-Cookie', cookie.serialize('token', data.jwt, { httpOnly: true, secure: process.env.NODE_ENV !== 'development', maxAge: 60 * 60 * 24 * 7, // 1 week sameSite: 'strict', path: '/', }) ) res.status(200).json({ user: data.user }) } else { res .status(data.statusCode) .json({ message: data.message[0].messages[0].message }) } } else { res.setHeader('Allow', ['POST']) res.status(405).json({ message: `Method ${req.method} not allowed` }) }Esta es mi función de registro en mi contexto.
const register = async (user) => { const res = await fetch(`${NEXT_CLIENT_URL}/api/register`, { method: 'POST', headers: { 'Content-Type': 'application/json', }, body: JSON.stringify(user), }) const data = await res.json() if (res.ok) { setUser(data.user) router.push('/account/dashboard') } else { setError(data.message) setError(null) } }Así es como llamo a la función de contexto en mi próxima interfaz
const handleSubmit = (e) => { e.preventDefault() if (password !== password2) { toast.error('Passwords do not match!') return } register({ username, email, password }) }¡Me alegro por cada consejo! El inicio de sesión funciona como se esperaba en la misma aplicación.