无法将数据从 useState 发布到 Mysql
P粉368878176
P粉368878176 2024-04-03 10:53:49
0
1
410

我试图将输入数据从 useState 发布到 Mysql,但它没有发生。虽然我能够将数据从数据库获取到页面,但是当涉及到发布时,当有很多值时,我不知道如何将数据从状态挂钩发送到 mysql。 请看一下


我发送表单数据的代码

import React,{useState , useRef} from "react";
import "./AddProjects.css"
import axios from "axios";
import Projects from "../Projects/Projects";
import {BiChevronLeftCircle,BiChevronRightCircle} from "react-icons/bi"

export default function AddProjects() {
    
    
    const [AddProjects,setAddProjects] = useState({
        ProjectName:"",
        Discription:"",
        git:"",
        Img:""
    })


    const [getQuery,setGetQuery] = useState({
        projectList:[]
    })


    const inputFile = useRef(null)


    function handleChange(e) {
        const {name , value} = e.target;
        setAddProjects(newProjects => ({
            ...newProjects,[name]:value
        }))


    }
    function imgChange(e) {
        setAddProjects({ ...AddProjects, Img: URL.createObjectURL(e.target.files[0]) });
    }


    function getProjectList() {
        axios.get(`http://localhost:3060/projects`)
        .then((response) => response.data)
        .then(response2 => {
            setGetQuery({projectList : response2})
        })
    }

    function onSubmitHandler(e) {
        axios.post(`http://localhost:3060/addProjects`,{
                ProjectName: AddProjects.ProjectName,        
                Discription:AddProjects.Discription,
                git:AddProjects.git,
                Img:AddProjects.Img
        })
        getProjectList()
    }
    return(
        <>
            <div className="AddProjects">  
                <form onSubmit={onSubmitHandler} method="POST" encType="multipart/form-data" >
                    <h2>Add New Project</h2>
                    <input  type="text" placeholder="Project Name..."     name="ProjectName" onChange={handleChange}/>
                    <input  type="text"   placeholder="Project Discription..."   name="Discription" onChange={handleChange}/>
                    <input  type="text"   placeholder="Git Repository/Code..."    name="git" onChange={handleChange}/>
                    <input type="file"  accept="image/jpg,image/jpeg" name="Img" onChange={imgChange} ref={inputFile} />
                    <button type="button"onClick={() => inputFile.current.click()}>Add New Image</button>
                    <button type="submit" >Submit Project</button>
                </form>
                <button onClick={getProjectList}>click me </button>
            </div>
            <div>
                <div className="Section-Projects" >
                <h1>My Projects </h1>
                {/* <Link to={checkBox?'/AddProjects':""} ><button className="Add-newProject" onClick={onStateChange}><IoIosAddCircleOutline/></button></Link>  */}

                <div className="Projects">
                    <button className="arrowLeft"><BiChevronLeftCircle /></button>
                            <div className="Single">
                                {getQuery.projectList.map((gettingQuery) => 
                                    <Projects   
                                    ProjectId={gettingQuery.ProjectId}
                                    ProjectName={gettingQuery.ProjectName}
                                    Discription={gettingQuery.Discription}
                                    git={gettingQuery.git}
                                    Img={gettingQuery.Img}
                                        />
                                )}
                            </div>
                        <button className="arrowRight"><BiChevronRightCircle /></button>
                    </div>
                </div>
            </div>
                </> 
    )

};

正如你所看到的,我想将 4 件事发送到 mysql 表,但我不认为这是这样做的方法,我只是无法弄清楚


正在发送数据的文件的代码

const express = require('express');
const cors = require('cors')
const PORT = 3060;
const db  = require('./Database')

const bodyParser = require('body-parser');
const { response } = require('express');

const app = express();

app.use(cors());
app.use(bodyParser.json());

app.get('/projects', (req,res) => {
    const TASK_QUERY = `SELECT * FROM  addprojects.newproject`;
    db.query(TASK_QUERY , (err, response) => {
        if(err) res.status(404).send('somthings wrong')
        else res.send(response)
    })
});

app.post('/addProjects', (req,res) => {
    const ADD_QUERY = `INSERT INTO addprojects.newproject VALUES('${req.body.data}')`;
    db.query(ADD_QUERY, (err) => {
        if (err) console.log(err)
        else res.send('Query added sucsessfully')
    })
    
} );

app.listen(PORT, () => {
    console.log('app is listning to port 3000')
})

我认为虽然发布方法是正确的,但价值并不正确,所以请帮助我,我已经为此呆了 2 天任何建议都会有帮助

P粉368878176
P粉368878176

全部回复(1)
P粉376738875
INSERT INTO tablename (columnName1, columnName2) VALUES ('Company Inc', 'Highway 37')

对于后端:

你不提及列名,它不知道哪个字段属于表中的哪一列。

对于前端:

axios.post(`http://localhost:3060/addProjects`,{
            ProjectName: AddProjects.ProjectName,        
            Discription:AddProjects.Discription,
            git:AddProjects.git,
            Img:AddProjects.Img
    })

ProjectName,Discription,git,Img 使这些键名称与您的列名称完全相同。 并且您要在此 api 中上传图像,因此请在 formdata 中从前面转换数据,然后在 api 中传递该数据,在后端,您将在 formdata 中将该数据传递给

热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板