Home > Net >  How to properly axios post from React frontend to express backend?
How to properly axios post from React frontend to express backend?

Time:04-10

I'm struggling a LOT to get a simple response from my api server to my react app.

My architecture looks like this:

react post request with axios ----->>>>  node api sever with express 

It DOES post to my database, but why do I don't get any reponse back with axios and its works with insomnia ??? It's becoming frustrating since I don't get any error!

Why do I don't get any response from axios? Insomnia does get it! I'm so confused....

insomnia response: enter image description here

insomnia headers:

X-Powered-By: Express
Access-Control-Allow-Origin: *
Access-Control-Allow-Methods: *
Access-Control-Allow-Headers: *
Access-Control-Allow-Credentials: true
Content-Type: application/json; charset=utf-8
Content-Length: 153
ETag: W/"99-Qxu9/fOKmJfU8A3jhWmwX27kAX4"
Date: Sat, 09 Apr 2022 17:17:20 GMT
Connection: keep-alive
Keep-Alive: timeout=5

database:

> db.users.find()
{ "_id" : ObjectId("6251bfa0ce679f061d8c0c52"), "email" : "[email protected]", "password" : "$2b$04$Teu4TkNlN4oFn0ihEZ4YwuLFn8p8SON9uqzAGvShak.Tn0IW88PPq", "dbo" : "1999-30-12", "phone" : "123456789", "createdAt" : ISODate("2022-04-09T17:17:20.861Z"), "__v" : 0 }

Post with chrome react mocked code:

enter image description here

> db.users.find()
{ "_id" : ObjectId("6251bfa0ce679f061d8c0c52"), "email" : "[email protected]", "password" : "$2b$04$Teu4TkNlN4oFn0ihEZ4YwuLFn8p8SON9uqzAGvShak.Tn0IW88PPq", "dbo" : "1999-30-12", "phone" : "123456789", "createdAt" : ISODate("2022-04-09T17:17:20.861Z"), "__v" : 0 }
{ "_id" : ObjectId("6251c08ece679f061d8c0c55"), "email" : "[email protected]", "password" : "$2b$04$t8z7qriXwLMvXrebxu5Aiu0fmC8dWoVWgSsN6E7vvKC38K5M7XJA2", "dbo" : "1999-30-12", "phone" : "123456789", "createdAt" : ISODate("2022-04-09T17:21:18.267Z"), "__v" : 0 }
> 

my files (node and react):

registerController.js

const express = require('express');
const router = express.Router();
const User = require('../models/userSchema');
  
router.post('/register', async (req,res) => {
    const { email } = req.body;
    console.log(req.body);
    try{
        if( await User.findOne({ email }) ){
            return res.status(400).send({ error: 'User already registred'});
        }
        const user = await User.create(req.body);
        user.password = undefined; 
        return res.status(200).send({ user });
    } catch (error) {
        return res.status(400).send({
            error: 'Regstration failed'
        });
    }
});

module.exports = app => app.use('/auth', router);

Register.js

import React from 'react';
import { Button, TextField, Box, Typography } from '@material-ui/core';
import sendUserRegistration from './controllers/apiRegister';

class Register extends React.Component{
  constructor(props){
    super(props);
    this.state = { 
      email: '',
      password: '',
      dob: '',
      phone: ''
    };
    this.handleSubmit = this.handleSubmit.bind(this);
    this.handleChangeEmail = this.handleChangeEmail.bind(this);
    this.handleChangePassword = this.handleChangePassword.bind(this);
    this.handleChangeDob = this.handleChangeDob.bind(this);
    this.handleChangePhone = this.handleChangePhone.bind(this);
  }

  handleChangeEmail(event) {    
    // console.log(event.target.value)
    this.setState({
      email: event.target.value
    });  
  }

  handleChangePassword(event) {    
    // console.log(event.target.value)
    this.setState({
      password: event.target.value
    });  
  }
  handleChangeDob(event) {    
    // console.log(event.target.value)
    this.setState({
      dob: event.target.value
    });  
  }
  handleChangePhone(event) {    
    // console.log(event.target.value)
    this.setState({
      phone: event.target.value
    });  
  }

  async handleSubmit() {
    console.log(this.state)
    const responseStatus = await sendUserRegistration(this.state);
    console.log( 'RESPONSE: '   responseStatus);
    alert(responseStatus);
  }

  render(){
    return (
      <>
      <form onSubmit={this.handleSubmit}>
        <Box
          display='flex'
          flexDirection='row'
          justifyContent='center'
          >
            <Box 
              display='flex'
              flexDirection='column'
              justifyContent='center'
              >
                  <Typography 
                    variant="h3" component="h3"
                    >
                      Register
                  </Typography>
                  <TextField
                    id="email"
                    name="email"
                    label="Email"
                    type="email"
                    // value={this.state.email} 
                    onChange={this.handleChangeEmail}
                  />
                  <TextField
                    id="password"
                    name="password"
                    label="Password"
                    type="password"
                    // value={this.state.email} 
                    onChange={this.handleChangePassword}
                  />
                  <TextField
                    id="dob"
                    name="dob"
                    label="Day of birth"
                    type="date"
                    // value={this.state.email} 
                    onChange={this.handleChangeDob}
                  />
                  <TextField
                    id="phone"
                    name="phone"
                    label="Phone"
                    type="phone"
                    // value={this.state.email} 
                    onChange={this.handleChangePhone}
                  />
                                    
                  <Button 
                    variant="contained"
                    type='submit'
                    >
                      Register!
                  </Button>
            </Box>
          </Box>
      </form>
      </>
    );
  }
}

export default Register;

apiRegister.js

const axios = require('axios');

function sendUserRegistration(user){
  return new Promise( 
    returnPromise => {
      const api_endpoint = process.env.REACT_APP_API_ENDPOINT;
      console.log("1")
      console.log(api_endpoint)
      console.log(user)
      try{
        console.log('1.1')
        axios.post(`http://${api_endpoint}/auth/register`,{
          "email":"[email protected]",
          "password":"test123",
          "dbo":"1999-30-12",
          "phone":"123456789"
        })
        .then(function (response) {
          console.log("2")
          console.log(response);
          returnPromise(response);
        })
        .catch(function (error) {
          console.log("3")
          console.log(error);
          returnPromise(error);
        }).then(function(){
          console.log("4")
        });
        console.log('1.2')
      } catch (err){
        console.log('1.3')
        console.log(err)
      }
    }
  );
}

module.exports = sendUserRegistration;

CodePudding user response:

Try this out!

async handleSubmit(event) {
  event.preventDefault()
  try {
  const responseStatus = await sendUserRegistration(this.state);
  } catch (error) {
    console.log(error);
  }
}

apiRegister.js

export const sendUserRegistration = async (user) => {
  const api_endpoint = process.env.REACT_APP_API_ENDPOINT;
  try {
    const res = axios.post(`http://${api_endpoint}/auth/register`, {
      email: "[email protected]",
      password: "test123",
      dbo: "1999-30-12",
      phone: "123456789",
    });
    return res;
  } catch (err) {
    throw new Error(err);
  }
};

CodePudding user response:

Solved, it was a react problem. Thanks to @Abbas Hussain for the help!

 async handleSubmit(event) {
    try{
      event.preventDefault(); 
      console.log(this.state)
      const responseStatus = await sendUserRegistration(this.state);
      console.log( 'RESPONSE: '   responseStatus);
      alert(responseStatus);
    } catch (e){
      console.log(e)
    }
  }

  render(){
    return (
      <>
      <form onSubmit={(event) => this.handleSubmit(event)}>
        <Box
          display='flex'
          flexDirection='row'
          justifyContent='center'
          >
  • Related