signup.js
const SignupForm = () => {
const [username, setUsername] = useState("");
const [password, setPassword] = useState("");
const handleSignup = () => {
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={ () => handleSignup() }>Sign up</button>
</div>
)
}
function from auth.js in backend server
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 newUser = new User({ username, password })
newUser.save()
.then(user => {
response.json({ message: "Account Saved Successfully"})
})
.catch(error => {
console.log(error)
})
})
Encountering issue - The json object being posted from signup.js appears to have an undefined body. I've declared username as a constant earlier in the function. Unsure how to resolve this.