簡體   English   中英

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

[英]How does one prevent a form from redirecting me? using ReactJS and ExpressJS

所以我有一個表單,當我提交它時,它會將我重定向到路由 /repair,表單的操作是 /repair。

然而,我希望它做的是將其全部保留為 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',
        ...
    })
}

然后,在onSubmit方法form聲明它:

<form onSubmit={handleSubmit}>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM