无法将数据从useState发布到Mysql

5t7ly7z5  于 2023-01-04  发布在  Mysql
关注(0)|答案(1)|浏览(111)

我试图发布输入数据从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天任何建议将是帮助充分

kknvjkwl

kknvjkwl1#

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

相关问题