I have an application that makes a POST request on submitting the form. But when the request is on the server, I cannot get the body of the request.
This is my ReactJS code:
const onSubmit = async event => {
try {
event.preventDefault()
const response = await fetch('/api/auth/login', {
method: 'POST',
mode: 'no-cors',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ email, password })
})
const result = await response.json()
} catch (e) {
console.error(e)
}
}
return (
<>
<h1>Authorisation</h1>
<form onSubmit={onSubmit}>
<input name="email" value={email} onChange={e => setEmail(e.target.value)} />
<input name="password" value={password} onChange={e => setPassword(e.target.value)} type="password"/>
<button type="submit">Submit</button>
</form>
</>
)
In my backend I have Express:
app.use(express.json())
const login = async (req, res) => {
try {
console.log(req.body) // here is always {}
const {email, password} = req.body
/*some code*/
} catch (e) {
console.log('Login error: ' + e)
}
}
router.post('/login', login)
app.use(router)
I notice you are using no-cors
mode . When you use that mode , it limits certain headers.
For example this type of mode only lets the Content-Type
become application/x-www-form-urlencoded
, multipart/form-data
, or text/plain
. You can read more here
I suggest you just use cors
mode so you can use application/json