我在一个数据库中有一个预先创建的表,我想从前端(即由用户)插入值,但由于某种原因,我写的代码未能实现我所寻求的:/
我仍然是一个初学者,所以对我苛刻,让我通过记住我在这里面临的学习。
下面是服务器端的代码:
const express = require("express");
const app = express();
const cors = require("cors");
const pool = require("./db");
const bodyParser = require("body-parser");
app.use(bodyParser.json());
app.use(cors());
app.use(express.json());
// input values
app.put("/admin/staff", async (req, res) => {
try {
const {adminstration} = await req.body;
// contains the admin table details to be added
const newadminstration = await pool.query("INSERT INTO adminstration (adminstration) VALUES ($1) RETURNING *", [adminstration]);
res.json(newadminstration.rows[0]);
console.log(newadminstration)
} catch (err) {
console.error(err.message);
}
});
app.listen(5000, () => {
console.log("server is running on port 5000")
});
下面是代码的前端:
import React from 'react';
import { useState } from 'react';
import Box from '@mui/material/Box';
import TextField from '@mui/material/TextField';
import { Input} from '@mui/material';
export default function Adminfun() {
const [adminstration, setadminstration] = useState({admin_name:"", admin_email:"", admin_password:""});
const bbb= async (e) => {
e.preventdefault();
try {
const body = { adminstration };
const response = await fetch("http://localhost:5000/admin/staff", {
method: "PUT",
headers: {"Content-Type": "application/json"},
body: JSON.stringify(body)
});
console.log(response)
} catch (err) {
console.error(err.message)
}
}; return (
<Box
component="form"
sx={{
'& > :not(style)': { m: 1, width: '25ch' },
}}
noValidate
autoComplete="off">
<TextField id="outlined-basic" label="Name" variant="outlined" value={adminstration.admin_name}
onChange={(Event) =>
{const newAdminstration = {...adminstration};
newAdminstration.admin_name = Event.target.value;
setadminstration(newAdminstration)}}/>
{/* {setadminstration({...adminstration, admin_name: Event.target.value})}}/> */}
<TextField id="filled-basic" label="Email" variant="filled" value={adminstration.admin_email}
onChange={(Event) =>
{setadminstration({...adminstration, admin_email: Event.target.value})}}/>
<TextField id="standard-basic" label="Password" variant="standard" value={adminstration.admin_password}
onChange={(Event) =>
{const newAdminstration = {...adminstration};
newAdminstration.admin_password = Event.target.value;
setadminstration(newAdminstration)}}/>
<br></br>
<Input type='submit' onSubmit={bbb} >Submit</Input>
</Box>)
};
node js用于后端,postgresql数据库,react用于前端。
1条答案
按热度按时间mwyxok5s1#
更新:根据我的高级- @AdrianKlaver -命令,我成功地解决了这个问题,尽管发现了另一个问题-为此,我发布了一个单独的问题-这里是更新的代码:
经过进一步的测试,我发现这个问题从一开始就与事务无关,而是需要我进一步解构json对象,因为数据库出于某种原因不接受它。
在这里,它正在对原始代码进行一些编辑: