简体   繁体   中英

how to solve error while using Axios in react

Client/App.js:

import React, { useState, useEffect } from "react";
import Axios from "axios";
const App = () => {
  const [movieName, setmovieName] = useState("");
  const [movieReview, setmovieReview] = useState("");
  const [getReview, setgetReview] = useState([]);

  useEffect(() => {
    Axios.get("http://localhost:3001/api/get", (result) => {
      console.log(result.data);
      setgetReview(result.data);
    });
  }, []);

  const submitReview = () => {
    Axios.post("http://localhost:3001/api/insert", {
      movieName: movieName,
      movieReview: movieReview
    })
      .then(() => {
        alert("Success");
      })
      .catch((e) => alert(e));
  };
  return (
    <div className="index">
      <h2>movie name</h2>{" "}
      <input type="text" onChange={(e) => setmovieName(e.target.value)} />
      <h2>movie rating</h2>{" "}
      <input type="text" onChange={(e) => setmovieReview(e.target.value)} />
      <button onClick={submitReview}>submit</button>
      {getReview.map((val) => {
        return (
          <h1>
            Movie name : {val.movieName} Movie review: {val.movieReview}
          </h1>
        );
      })}
    </div>
  );
};

export default App;

Server/index.js:

const express = require("express");
const mysql = require("mysql");
const cors = require("cors");
const bodyParser = require("body-parser");

const app = express();
app.use(bodyParser.urlencoded({ extended: true }));
app.use(cors());
app.use(express.json());

const db = mysql.createConnection({
  host: "localhost",
  root: "root",
  password: "",
  database: "crudatabase"
});

db.connect((err) => {
  if (err) throw err;
});

app.get("/api/get", (req, res) => {
  const selectStmt = "SELECT movieName,movieReview FROM movie_review;";
  db.query(selectStmt, (err, result) => {
    res.send(result);
  });
});

app.post("/api/insert", (req, res) => {
  const movieName = req.body.movieName;
  const movieReview = req.body.movieReview;
  const insertStmt =
    "INSERT INTO movie_review (movieName,movieReview) VALUES (?,?);";
  db.query(insertStmt, [movieName, movieReview], (err, result) => {
    console.log(err);
  });
});

app.listen(3001, () => {
  console.log("Server running on 3001");
});

In the above react and express code I am able to insert the data in the database but after inserting then() part in client is not working. Also the useEffect is not working. I tried many ways but not able to get the reason. I would be glad if someone can solve me the error and all the dependencies are already installed.

  1. In your useEffect , you're passing a callback to Axios.get - this is not consistent with the Axios API (you even do it correctly in the submitReview function:):
useEffect(() => {
    // change to Promise.then() chain
    Axios.get("http://localhost:3001/api/get").then((result) => {
      console.log(result.data);
      setgetReview(result.data);
    });
  }, []);
  1. Your then() chain is not working because your POST response handler never returns a status or a response! Just like in your GET handler, your POST handler needs to let the client know that a request has been successful. eg res.send(/*...*/) or even just res.sendStatus(200) .

As you are dealing with the promise and have used the thenable syntax while submitting the values but you are not using it while getting the values. try using the below code and check whether this resolves your problem. One more concise method to deal with promises is to use async/await try to use the below code hopes this resolves your problem.

    useEffect(() => {
    const getMovies = async () => {
      try {
        let { data } = await Axios.get("http://localhost:3001/api/get");
        console.log(data);
        setgetReview(data);
      } catch (error) {
        console.log(error);
      }
    };

    getMovies();
  }, []);

Your useEffect is returning a promise try to use async await or.then on your code.

Try to change it from:

useEffect(() => {
        Axios.get("http://localhost:3001/api/get", (result) => {
          console.log(result.data);
          setgetReview(result.data);
        });
      }, []);

To:

useEffect(() => {
      const get_data = async () => {
         try {
           const result = await Axios.get("http://localhost:3001/api/get")
           console.log(result.data)
           setgetReview(result.data)
         } catch (e) {
           console.log(e)
         }
      }

      get_data()
}, []);

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