搜尋

首頁  >  問答  >  主體

無法將資料從 useState 發佈到 Mysql

我試圖將輸入資料從 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粉368878176P粉368878176265 天前426

全部回覆(1)我來回復

  • P粉376738875

    P粉3767388752024-04-04 00:51:35

    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 中將該數據傳遞給

    回覆
    0
  • 取消回覆