[英]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.
如果有人可以解决我的错误并且已经安装了所有依赖项,我会很高兴。
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
, 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);
});
}, []);
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.