我试图将输入值推送到数据库,问题是我没有得到任何返回错误,并且server.js第24行中req-body的控制台日志为空,我在控制台中看不到任何东西。我通过app.jsx第18行的post请求发送输入值,并假设在server.js第24行看到控制台日志。有人能帮我做错事吗?
import { useState, useEffect } from "react";
import axios from "axios";
import Task from "./Task";
import "./App.scss";
function App() {
//Value of Input
const [val, setVal] = useState("");
const [todos, setTodos] = useState([]);
const [message, setMessage] = useState([]);
const addTodos = async (e) => {
if (val == "") return;
e.preventDefault();
await axios
.post("http://localhost:8000/message", { todos })
.then((response) => console.log(response))
.catch((error) => console.log(error));
/** */
setTodos([...todos, val]);
setVal("");
/** */
};
useEffect(() => {
const fetchProducts = async () => {
const res = await axios.get("http://localhost:8000/message");
setMessage(res.data);
};
fetchProducts();
}, []);
const handleDelete = (id) => {
setTodos(todos.filter((_, key) => key !== id));
}; //#endregion
return (
<div className="App">
{/** On change values*/}
<form onSubmit={addTodos}>
<input
onChange={(e) => setVal(e.target.value)}
value={val}
type="text"
/>
<button type="submit">Add</button>
</form>
<ul>
{todos.map((todo, key) => (
<Task todo={todo} key={key} myKey={key} handleDelete={handleDelete} />
))}
</ul>
{message.map((e) => (
<div>{e.todo}</div>
))}
</div>
);
}
export default App;
//server.js
const express = require("express");
const cors = require("cors");
const { Client } = require("pg");
const client = new Client({
user: "jj",
host: "localhost",
database: "dbname",
password: "rootuser",
port: 5432,
});
client.connect();
const app = express();
app.use(cors());
app.use(express.json());
app.get("/message", async (req, res) => {
const { rows } = await client.query(`SELECT * from todo`);
res.send(rows);
});
app.post("/message", (req, res) => {
const { todos } = req.body;
console.log(todos);
return res.status(201).json(todos);
});
app.listen(8000, () => {
console.log(`Server is running on port 5174.`);
});
这里您在<form onSubmit={addTodos}></form>
行中使用onSumit
如果你使用onSubmit
,那么你应该在react-中通过以下方式绑定数据
var bodyFormData = new FormData();
bodyFormData.append('todos', todos);
然后将这个bodyFormData
发送到api-
axios({
method: "post",
url: "myurl",
data: bodyFormData,
headers: { "Content-Type": "multipart/form-data" },
})
.then(function (response) {
//handle success
console.log(response);
})
.catch(function (response) {
//handle error
console.log(response);
});