When I try to call the POST Api through fetch method by passing the parameter in body then I got req.body undefined on backend side(Node js side).Also when I call the Same POST api through Postman by passing the parameter in body then It work successfully(I got the req.body). backend is in node js and Front end is in React js. Any help will be appreciated.

import React, { Component } from 'react'
import '../Css/Login.css'
export class Login extends Component {
constructor(props) {
super(props)
this.state = {
name: "",
password: ""
}
this.onChange = this.onChange.bind(this);
}
submitHandler = (e) => {
e.preventDefault();
console.log(this.state);
try {
let result = fetch('http://localhost:4000/users/login', {
method: 'POST',
mode: 'no-cors',
headers: {
'Content-Type': 'application/json',
'Accept': 'application/json'
},
body: { name: this.state.name, password: this.state.password }
})
result.then((sucess) => { console.log(sucess) })
} catch (error) {
console.log(error)
}
}
onChange(e) {
this.setState({ [e.target.name]: e.target.value })
}
render() {
return (
<div>
<div className="LoginPage">
<div class="container Login_div">
<div className="Admin_panel"><h2>Admin Panel</h2></div>
<form onSubmit={this.submitHandler}>
<div class="form-group">
<label for="email">Email:</label>
<input type="text" name="name" class="form-control" placeholder="Enter email" onChange={this.onChange} />
</div>
<div class="form-group">
<label for="pwd">Password:</label>
<input type="password" name="password" class="form-control" placeholder="Enter password" onChange={this.onChange} />
</div>
<button type="submit" class="btn btn-login">Submit</button>
</form>
</div>
</div>
</div>
)
}
}
export default Login
Is this use node-fetch? So I think you need to add JSON.stringify() to body.
try {
let result = fetch('http://localhost:4000/users/login', {
method: 'POST',
mode:'no-cors',
headers: {
'Content-Type':'application/json',
'Accept':'application/json'
},
body: JSON.stringify({ name: this.state.name, password: this.state.password })
});
result.then((success) => { console.log(success) });
} catch (error) {
console.log(error);
}
Link refers Node Fetch - post with json. I hope it works.
UPDATE If your backend is using ExpressJs make sure you added.
const app = express();
// push them above the router middleware!
// parse application/x-www-form-urlencoded
app.use(express.urlencoded({ extended: true }));
// parse application/json
app.use(express.json());
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With