我在客户端使用React.js,在服务器端使用Express.js。当使用POST方法将数据从客户端发送到服务器并将其保存在json文件中时,我得到以下错误:
screenshot of the error message
这是客户端代码:
import { useState, useRef } from "react";
import NavBar from "./NavBar";
const AddMovie = () => {
const [movieData, setMovieData] = useState({});
const clearFormInput = useRef(null);
const formDataHandler = (e) => {
setMovieData({
...movieData,
[e.target.name]: e.target.value,
});
};
const submitDataHandler = (e) => {
e.preventDefault();
fetch("http://localhost:3001/add", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(movieData),
})
.then((response) => {
return response.json();
})
.then((data) => console.log(data))
.catch((error) => console.error(error));
clearFormInput.current.reset();
};
return (
<div>
<NavBar />
<form
onSubmit={submitDataHandler}
ref={clearFormInput}
className="m-auto p-5 w-[30rem] bg-blue-400 relative top-60 transform -translate-y-1/2"
>
<div className="flex flex-col">
<label htmlFor="title">Movie Title</label>
<input
onChange={formDataHandler}
type="text"
name="title"
id="title"
required
/>
</div>
<div className="flex flex-col">
<label htmlFor="whereToWatch">Where do we find it?</label>
<input
onChange={formDataHandler}
type="text"
name="whereToWatch"
id="whereToWatch"
placeholder="e.g. NetFlix"
required
/>
</div>
<div className="flex flex-col">
<label htmlFor="description">Tell us about the movie</label>
<textarea
onChange={formDataHandler}
name="description"
id="description"
type="text"
required
/>
</div>
<button className="my-4 p-3 bg-blue-950 text-white rounded-md">
Share Movie
</button>
</form>
</div>
);
};
export default AddMovie;
这是服务器端代码:
const express = require("express");
const cors = require("cors");
const uuid = require("uuid");
const path = require("path");
const fs = require("fs");
const app = express();
app.use(
cors({
origin: "http://localhost:5174",
})
);
app.use(express.json());
app.get("/", (req, res) => {
res.send("server is running...");
});
app.post("/add", (req, res) => {
const movieData = req.body;
console.log(movieData)
movieData.id = uuid.v4();
const filePath = path.join(__dirname, "data", "movies.json");
const fileData = fs.readFileSync(filePath);
const existingMovies = JSON.parse(fileData);
existingMovies.push(movieData);
fs.writeFileSync(filePath, JSON.stringify(existingMovies));
});
app.listen(3001);
我试图将数据保存在movie.json文件中,它似乎正在工作,但我仍然在控制台上得到该错误。我真的很感激你的帮助。谢谢
1条答案
按热度按时间jtjikinw1#
您需要等待获取调用