如何防止表单重定向?使用ReactJS和ExpressJS



我有一个表单,当我提交它时,它将我重定向到路由/修复,表单的动作是/修复。

然而,我想让它做的是,把它作为一个SPA,所以当表单提交时,字段被删除,它只是说"谢谢你"或者类似的东西。有办法做到吗?

前端:

import React, { useState } from "react";
import { Grid, TextField, Button } from "@mui/material";
function Form(props) {
let [data, setData] = useState({
firstName: "",
lastName: "",
email: "",
phone: "",
request: "",
});
const handleChange = (event) => {
setData({ ...data, [event.target.name]: event.target.value });
event.preventDefault();
};
return (
<React.Fragment>
<form action='/repair' method='POST'>
<Grid container spacing={2}>
<Grid item xs={6}>
<TextField
sx='width: 80%'
id='form-first-name'
label='First Name'
variant='outlined'
name='firstName'
/>
</Grid>
<Grid item xs={6}>
<TextField
sx='width: 80%'
id='form-last-name'
label='Last Name'
variant='outlined'
name='lastName'
/>
</Grid>
<Grid item xs={12}>
<TextField
sx='width: 90%'
id='form-email'
label='Email'
variant='outlined'
name='email'
/>{" "}
</Grid>
<Grid item xs={12}>
<TextField
sx='width: 90%'
id='form-phone'
label='Phone'
variant='outlined'
name='phone'
/>{" "}
</Grid>
<Grid item xs={12}>
<TextField
id='outlined-multiline-static'
multiline
rows={4}
placeholder='Let us know what your issue is:'
sx='width: 90%'
name='request'
/>
</Grid>
<Grid item xs={12}>
<Button id='submit-repair-request' type='submit' variant='contained'>
Submit
</Button>
</Grid>
</Grid>
</form>
</React.Fragment>
);
}
export default Form;

后端:

const express = require('express');
const app = express();
const http = require('http').Server(app);
const io = require('socket.io')(http);
const path = require('path');
const crypto = require('crypto');
const mysql = require('mysql');
const db = mysql.createConnection({
host:   'localhost',
user:   'root',
password:   '',
database:   'dos-bros-it',
});
db.connect((err) => {
if(err) {
console.log(err.code);
console.log(err.fatal);
}else{
console.log("Connection has been succesfully initiated!")
}
})
const PORT = 7072;
app.use(express.static(path.join(__dirname, "client/build/")));
app.use(express.urlencoded({extended: true}));
app.use(express.json());
app.get('/', (req, res) => {
res.sendFile(path.join(__dirname, "client/public/", "index.html"));
});
app.post('/repair', (req, res, next) => {
$query = "INSERT INTO tickets (firstName, lastName, email, phone, description) VALUES (?)";
$data = [
[req.body.firstName], 
[req.body.lastName],
[req.body.email], 
[req.body.phone], 
[req.body.request]
]
db.query($query, 
[$data], (err, rows, fields) => {
if (!err) { 
console.log('Repair was succesfully sent to the servers database! n Records: ' + rows);
}else{
console.log(err);
}
});
console.log(req.body.firstName, req.body.lastName, req.body.email, req.body.phone, req.body.request);

res.send("<h1>FORM SENT</h1>")
next();
})
io.on("connection", (socket) => {
console.log('Client has connected to the server!!!');
socket.on('test', (msg)=>{
console.log('recieved test message!!!', msg);
})
})
http.listen(PORT, ()=>{
console.log('Server Started using port:', PORT);
})

声明一个handleSubmit方法,其中处理form操作并在逻辑之前调用preventDefault():

const handleSubmit = (e) => {
e.preventDefault();
fetch(`/repair`, {
method: 'POST',
...
})
}

然后在formonSubmit方法中声明:

<form onSubmit={handleSubmit}>

最新更新