Home > Software engineering >  How to connect backend create user function to front end (Node.js, React.js, MongoDB)
How to connect backend create user function to front end (Node.js, React.js, MongoDB)

Time:04-22

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);

CodePudding user response:

Post request to this the API:

import axios from 'axios'

axios({
  method: 'post',
  url: '/api/users',
  data: {
    name: 'John',
    email: '[email protected]',
    password: 'Something'
  }
});

CodePudding user response:

You can use axios for example, an popular library: https://github.com/axios/axios

axios.post("URL", { email: "[email protected]" })

CodePudding user response:

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.

// User information
let username = 'boneless';

// Options for your request
let options = { method: 'POST', body: JSON.stringify({username: username});

let request = await fetch('url', { options });

let response = await request;

// Now you can apply logic to your response. Based on how your server replies.

I recommend reading up on fetch, as it's native in most browsers.

CodePudding user response:

You need to send POST request to the server (API ENDPOINT URL) from your frontend (react), you can achieve this using fetch api or axios

using fetch api (example) -

function createUser(userData) {
   try {
      const response = await fetch('API_ENDPOINT_URL', {
         method: 'POST',
         headers: {
           'Content-Type': 'application/json',
         },
         body: JSON.stringify(userData)
      })
      return response.json()
   }
   catch(error) {
     // handle error 
   }
}

using axios - (example)

function createUser(userData) {
   axios.post('API_ENDPOINT_URL', userData)
      .then((response)=> {
         return response.json()
      })
      .catch((error)=>{
         // handle error
      })
 }
  • Related