简体   繁体   中英

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.

刷新页面

client/package.json

{
  "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

错误

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM