In my Angular application, I am working on creating a registration page with validation. Once the user fills out the form and submits it, the data is sent to the server and saved in MongoDB.
This is the approach I have taken:
register_user() {
const data = this.register_form.getRawValue();
const formData: FormData = new FormData();
formData.append('name', data.name);
formData.append('email', data.email);
formData.append('password', data.password);
// formData.append('image', this.image);
formData.append('gender', 'Male');
formData.forEach((value, key) => {
console.log(value);
});
this.user_service.create_user(formData).subscribe((res) => {
console.log(res);
});
}
Service
create_user(data: FormData) {
return this.http.post(`${environment.BASE_URL}/user/create-user`, data, {
headers: { 'Content-Type': 'multipart/form-data' },
});
}
Node Server
// Required Route
const User = require('./Routes/user');
// Using Middleware
app.use(cors());
app.use(
express.urlencoded({
extended: true,
})
);
app.use(express.json());
app.use('/user', User);
app.listen(PORT, () => console.log(`App started on http://localhost:${PORT}`));
router.post('/create-user', async (req, res) => {
console.log(req.body);
let { name, email, gender, mobile_no, password } = req.body;
try {
if (
!(name && email && gender && mobile_no && password && password.length > 8)
) {
throw new Error(
`All fields are required - Name: ${name}, Email: ${email}, Gender: ${gender}, Mobile No: ${mobile_no}. Password length must be greater than 8 characters`
);
}
password = bcrypt.hashSync(password, parseInt(process.env.BCRYPT_SALT));
// let response = await USER.create({ name, email, gender, mobile_no });
const token = await jwt.sign(
{ name, email, mobile_no, user_id: response._id },
process.env.JWT_KEY
);
response = response.toObject();
response['token'] = token;
res.status(200).json({ err: 0, message: 'User Created', response });
} catch (error) {
res.status(404).json({ err: 1, message: error.message, error });
}
});
However, on the server, the request body is coming through as an empty object {}.
If I try to send a normal JavaScript object, it works fine.
How can I resolve this issue? Do I need to install or import any other modules in app.module.ts for FormData to work properly?