registro.js
const Signup = () => { const [username, Username] = useState(""); const [password, Password] = useState(""); const Post = () => { fetch("/signup", { method: "post", headers: { "Content-Type":"application/json", "Accept":"application/json", }, body: JSON.stringify({ username: "", password: "", }) }) .then(response => response.json()) .then(data => { console.log(data) }) } return ( <div> <input type="text" placeholder="username" value={username} onChange={ (e) => Username(e.target.value) }/> <br/> <input type="text" placeholder="password" value={password} onChange={ (e) => Password(e.target.value) }/> <br/> <button id="submit_button" onClick={ () => Post() }>Sign up</button> </div> ) }función de auth.js desde backend
router.post("/signup", (request, response) => { const username = request.body.username; const password = request.body.password; // If missing a field: error if (!username || !password) { response.status(422).json({ error: "Please add all fields" }) } // Checks if there already exists an account with that username user.findOne({ username: username }) .then ((saved_user) => { if (saved_user) { return response.status(422).json({ error: "There already exists an account with that username"}) } }) // Creates a new user and saves the account const user = new user({ username, password }) user.save() .then(user => { response.json({ message: "Account Saved Sucessfully"}) }) .catch(error => { console.log(error) }) })¿Alguien sabe lo que está mal? Parece que el objeto json que estoy publicando desde signup.js como un cuerpo indefinido por alguna razón. Sin embargo, ya declaré el nombre de usuario como una constante anteriormente en la función. IDK cómo arreglar eso.
Resuelto. Olvidé agregar App.use(express.json()); antes de las rutas.
No está dando el nombre de usuario y la contraseña en el cuerpo
body: JSON.stringify({ username: "", password: "", }). const Signup = () => { const [username, setUsername] = useState(""); const [password, setPassword] = useState(""); const Post = () => { fetch("/signup", { method: "POST", headers: { "Content-Type":"application/json", "Accept":"application/json", }, body: JSON.stringify({ username: username, password: password, }) }) .then(response => response.json()) .then(data => { console.log(data) }) } return ( <div> <input type="text" placeholder="username" value={username} onChange={ (e) => setUsername(e.target.value) }/> <br/> <input type="text" placeholder="password" value={password} onChange={ (e) => setPassword(e.target.value) }/> <br/> <button id="submit_button" onClick={ () => Post() }>Sign up</button> </div> ) }Trate de usar así, tal vez pueda funcionar.