im trying to send data from my frontend to my backend (React and NodeJS)
export default function UserFormPage(){
const [ username, setUsername ] = useState("")
const [ password, setPassword ] = useState("")
// MOVE TO A SERVICE
const setUsernameValue = (e) => {
setUsername(e.target.value)
}
const setPasswordValue = (e) => {
setPassword(e.target.value)
}
// MOVE TO A SERVICE
const handleSubmit = (e) => {
e.preventDefault()
const data = {username, password}
console.log(data)
return fetch("http://localhost:8080/users", {
method: "POST",
mode: "no-cors",
headers: { "Content-Type" : "application/x-www-form-urlencoded"},
body: data
})
}
return(
<div>
<form encType="application/x-www-form-urlencoded" onSubmit={handleSubmit}>
<input value={username} onChange={setUsernameValue} name="username" type="text"/>
<input value={password} onChange={setPasswordValue} name="password" type="text" /*CAMBIAR TYPE A PASSWORD*//>
<button type="submit">Submit</button>
</form>
</div>
)
}
and my backend is
app.post("/users", (req, res) => {
console.log(req.body)
res.send("working");
});
But the console.log is only displaying an empty object. I tested sending a POST request with Postman and it works fine so the problem is in my frontend
here is the correct implementation on react and nodejs express api with cors.
with this you can get the body object on server side whatever you put on the input boxes: