简体   繁体   English

在反应中使用 Axios 时如何解决错误

[英]how to solve error while using Axios in react

Client/App.js:客户端/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:服务器/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.在上面的反应和表达代码中,我能够在数据库中插入数据,但是在客户端中插入then()部分后不起作用。 Also the useEffect is not working. useEffect也不起作用。 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:): 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!您的then()链不起作用,因为您的 POST 响应处理程序从不返回状态或响应! Just like in your GET handler, your POST handler needs to let the client know that a request has been successful.就像在您的GET处理程序中一样,您的 POST 处理程序需要让客户端知道请求已成功。 eg res.send(/*...*/) or even just res.sendStatus(200) .例如res.send(/*...*/)甚至只是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.当您处理 promise 并在提交值时使用了 thenable 语法但在获取值时没有使用它。 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.处理 Promise 的一种更简洁的方法是使用 async/await 尝试使用下面的代码,希望这可以解决您的问题。

    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.您的 useEffect 正在返回promise尝试在您的代码上使用 async await or.then。

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()
}, []);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 使用 Axios 时如何解决 async-await 函数问题? - How to solve async-await function problem while using Axios? 使用 React 在 axios 中传递参数时出错 - Error while passing params in axios with React React 在使用 Axios 时在浏览器日志中抛出“Objects are not valid as a React child”错误 - React is throwing a “Objects are not valid as a React child” error in browser log while using Axios 尝试使用 axios POST 请求将信息发送到数据库时,如何解决此 422 错误? - How can I solve this 422 error when trying to send information to the database using an axios POST request? 如何解决:Axios 请求不起作用,而 Postman 可以? - How to solve: Axios request doesn't work while Postman can? 如何解决 axios promise - How to solve axios promise 反应 + Redux,使用 axios 更新 state 时出错 - React + Redux , error updating state using axios 使用 axios 发布日期时如何使用 react-toastify 承诺 - How I can use react-toastify promise while posting date using axios 如何处理 axios 中的 401(身份验证错误)并做出反应? - How to handle 401 (Authentication Error) in axios and react? 从反应 redux 解构数据时出错。 为什么它给出错误以及如何解决这个问题? - getting error while destructuring the data from react redux. why it is giving error and how to solve this?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM