Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Posting form response from react to node express with axios

I am not very sure why this isn’t working. I am trying to post from react to express using axios. I followed a tutorial on connecting react frontend to express server and it works for fetching data from server with a proxy. However, when I try to post data from react to the server, it does not work. I was prompted with two uncaught errors (cannot see them due to refresh) and then the page immediately refreshed with the form response posted to the url of the original react page instead of redirecting and posting to the server page with the form data.

refreshed page

client/package.json

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

{
  "name": "syllabus.io",
  "version": "0.1.0",
  "proxy": "http://localhost:8000/",
...

client/Login.js

import '../App.css';
import React, {useState} from 'react';
import axios from 'axios';

function Login() {
    const [data, setData] = useState({
      email: "",
      password: ""
    });

    function handleLogin(e) {
      e.preventDafault();
      console.log(data.email, data.password);
      axios
      .post('http://localhost:8000/api/login-post', data)
      .then(() => console.log('Book Created'))
      .catch(err => {
        console.error(err);
      });
    }

    function handleInput(e) {
      const newData={...data};
      newData[e.target.id] = e.target.value;
      setData(newData);
    }
    

    return ( 
    <div id="login" className="login">
        <body>
          <h1 id="title">Login</h1>
          <div class="form">
            <form onSubmit={(e) => handleLogin(e)}>
            <input type="text" onChange={(e) => handleInput(e)} className="email" name="email" value={data.email} id="email" placeholder="Email"/> 
            <input type="text" onChange={(e) => handleInput(e)} className="password" name="password" value={data.password} id="password" placeholder="Password"/> 
            <input id="Login" className="Login" type="submit" value="Login"/> 
            </form>
          </div>
        </body>
      </div>
    );
  }
export default Login;

server/server.js

const express = require('express');
const app = express();



app.use(express.json());
app.use(express.urlencoded({ extended: false }));


app.get("/api", (req, res) => {
    res.json({"user": ["userOne", "userTwo", "userThree"]})
})

app.post("/api/login-post", (req, res) => {
    console.log(req.body)
    res.send("Success")
})

app.listen(8000, () => {console.log('Server started on port 8000...')})

Edit:
The error, after checking preserve log, is

error

>Solution :

There is a typo in e.preventDefault(); in handleLogin function thus your form is submitted without a payload. I hope this fixes it.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading