我正在尝试为我的程序实施用户管理。我从MySQL表中获取所有已保存的用户,并将其发送到react前端。 现在,我想向该表添加一个新用户。我有一个Formik形式的4个文本字段。此表单具有onsubmit属性。 Onsubmit将输入传递给我的AddUser函数。 AddUser函数将变量放入数组中。 我的问题是,当我尝试使用axios将数据发布到后端时出现错误。
import React from 'react';
import { UserTable } from './UserTable';
import { AddUserForm } from './AddUserForm';
import axios from 'axios';
export function UserSettings() {
return (
<div>
<UserTable />
<AddUserForm onSubmit={({personalid, firstname, lastname, password}) => {AddUser(personalid, firstname, lastname, password )}} />
</div>
);
}
// send new user to back-end
async function AddUser(personalid: string, firstname: string, lastname: string, password: string) {
var user:string[] = [personalid, firstname, lastname, password]
console.log('before axios',user)
axios.post('http://localhost:3003/api/users/add', JSON.stringify(user))
.then(response => {
console.log('Data sent', response);
})
.catch(error => {
console.log('Send data failed', error);
})
};
// get users from front-end
routes.get('/api/users/add', (req, res) => {
const { data } = req.body;
AddUserDb(data);
});
// Add new user to database
export function AddUserDb(data:any): void {
var user: string[] = JSON.parse(data)
var personalidString: string = user[0]
var personalid:number = +personalidString
var firstname: string = user[1]
var lastname: string = user[2]
var password: string = user[3]
connectMySQL.query('INSERT INTO users (personalid, firstname, lastname, password) VALUES (?, ?, ?, ?) ;',
[personalid, firstname, lastname, password])
};
当我在AddUser表单中提交时,出现此错误: POST http://localhost:3003/api/users/add 500(内部服务器错误)