I am struggling in figuring out how to have a front-end that corresponds to my back-end in creating a user. I’ve successfully managed to create a user (can post to MongoDB using Insomnia) but don’t know what’s the structure for creating a user in the front end. Here’s what my code looks like:
Router
const express = require('express');
const router = express.Router();
router.post('/', async (req, res) => {
// First Validate The Request
const { error } = validate(req.body);
if (error) {
return res.status(400).send(error.details[0].message);
}
// Check if this user already exisits
let user = await User.findOne({ email: req.body.email });
if (user) {
return res.status(400).send('That user already exisits!');
} else {
// Insert the new user if they do not exist yet
user = new User({
name: req.body.name,
email: req.body.email,
password: req.body.password
});
await user.save();
res.send(user);
}
});
module.exports = router;
server.js
app.use('/api/users', users);
4
Answers
Post request to this the API:
You can use axios for example, an popular library: https://github.com/axios/axios
axios.post("URL", { email: "[email protected]" })
What you should do, is store information the user types in your frontend in a variable and pass this data to the fetch’s function via the
post
method.I recommend reading up on fetch, as it’s native in most browsers.
You need to send
POST
request to the server (API ENDPOINT URL
) from yourfrontend
(react), you can achieve this usingfetch api
oraxios
using
fetch api
(example) –using axios – (example)