linux 你好,当我打开浏览器的控制台时,我的代码工作[关闭]

r3i60tvu  于 11个月前  发布在  Linux
关注(0)|答案(1)|浏览(80)

**已关闭。**此问题需要debugging details。目前不接受回答。

编辑问题以包括desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem。这将帮助其他人回答问题。
7天前关闭
Improve this question
当我在Linux中打开浏览器的控制台时,我的代码工作并将数据插入数据库并将图像上传到文件夹中,但当我关闭终端数据时,数据不会插入数据库并仅上传图像,但在另一个人的计算机中也可以工作,请给予建议我该怎么做,这里是一个代码:react.js(检查MakePost()):

import React, { useEffect, useState } from 'react'
import axios from 'axios'

function Panel() {
    const [posts, setPosts] = useState([])
    const [gallery, setGallery] = useState([])
    const [uploadGallery, setUploadGallery] = useState([])
    const [galleryMessage, setGalleryMessage] = useState('')
    const [header, setHeader] = useState('')
    const [headerMessage, setHeaderMessage] = useState('')
    const [post, setPost] = useState('')
    const [postMessage, setPostMessage] = useState('')

    useEffect(() => {
        axios.get("http://localhost:3001/postsapi").then(response => {
            setPosts(response.data)
        }).catch(err => console.log(err))
        axios.get("http://localhost:3001/galleryapi").then(response => {
            setGallery(response.data)
        }).catch(err => console.log(err))
    }, [])

    const MakePost = (e) => {
        e.preventDefault()
        if (!uploadGallery || !header || !post) {
            if (!uploadGallery.length) {
                setGalleryMessage('The gallery field is required.')
            } else {
                setGalleryMessage('')
            }
            if (!header) {
                setHeaderMessage('The header field is required.')
            } else {
                setHeaderMessage('')
            }
            if (!post) {
                setPostMessage('The post field is required.')
            } else {
                setPostMessage('')
            }
        } else {
            setGalleryMessage('')
            setHeaderMessage('')
            setPostMessage('')
            const formData = new FormData()
            formData.append("header", header)
            formData.append("post", post)
            for (let i = 0; i < uploadGallery.length; i++) {
                const element = uploadGallery[i];
                formData.append("gallery", element)
            }
            axios.post("http://localhost:3001/makepost", formData).then(response => {
                if (response.data) {
                    console.log(response.data)
                }
            }).catch(err => console.log(err))
            axios.get("http://localhost:3001/postsapi").then(response => {
                setPosts(response.data)
            }).catch(err => console.log(err))
            axios.get("http://localhost:3001/galleryapi").then(response => {
                setGallery(response.data)
            }).catch(err => console.log(err))
        }
    }

    const DeletePost = (id) => {
        const formData = new FormData()
        formData.append("id", id)
        axios.post("http://localhost:3001/deletepost", formData).then(response => {
            if (response.data) {
                console.log(response.data)
            }
        }).catch(err => console.log(err))
        axios.get("http://localhost:3001/postsapi").then(response => {
            setPosts(response.data)
        }).catch(err => console.log(err))
        axios.get("http://localhost:3001/galleryapi").then(response => {
            setGallery(response.data)
        }).catch(err => console.log(err))
    }

    return (
        <>
            <div className='formcontainer'>
                <form onSubmit={MakePost}>
                    <div>
                        <label htmlFor="gallery">Gallery</label>
                        <input type="file" id="gallery" onChange={e => setUploadGallery(e.target.files)} accept='.jpg, .jpeg, .png' multiple />
                        <b>{galleryMessage}</b>
                    </div>
                    <div>
                        <label htmlFor="header">Header</label>
                        <textarea id="header" rows="10" value={header} onChange={e => setHeader(e.target.value)}></textarea>
                        <b>{headerMessage}</b>
                    </div>
                    <div>
                        <label htmlFor="post">Post</label>
                        <textarea id="post" rows="10" value={post} onChange={e => setPost(e.target.value)}></textarea>
                        <b>{postMessage}</b>
                    </div>
                    <button>Submit</button>
                </form>
            </div>
            <hr />
            {
                (posts.length) ? (
                    posts.map(post => (
                        <div className="post" key={`post${post.id}`}>
                            <div className='d-flex'>
                                <b>{post.header}</b>
                                <button onClick={() => DeletePost(post.id)}>Delete</button>
                            </div>
                            <div>
                                <b>{post.post}</b>
                            </div>
                            <hr />
                            <div>
                                {
                                    (gallery.filter(file => file.postid === post.id).length) ? (
                                        gallery.filter(file => file.postid === post.id).map(file => (
                                            <div key={`file${file.id}`}>
                                                <img src={`${process.env.PUBLIC_URL}/gallery/${file.name}`} alt={file.name} />
                                            </div>
                                        ))
                                    ) : (<></>)
                                }
                            </div>
                        </div>
                    ))
                ) : (
                    <h1>Posts don't exist.</h1>
                )
            }
        </>
    )
}

export default Panel

字符串
Node.js/express.js(请检查makepost post请求):

const express = require('express')
const app = express()
const port = 3001
const mysql = require('mysql');
const cors = require('cors')
const multer = require('multer')
const fs = require('fs')

app.use(cors())
app.use(express.json())
app.use(express.urlencoded({ extended: true }))

const con = mysql.createConnection({
    host: "localhost",
    user: "root",
    password: "",
    database: "top_gardering"
})

con.connect(function (err) {
    if (err) {
        console.log(err)
    }
})

const storage = multer.diskStorage({
    destination: (req, file, cb) => {
        cb(null, '../client/public/gallery')
    },

    filename: (req, file, cb) => {
        const min = 0
        const max = 999
        cb(null, "TOP_GARDERING_" + Date.now() + Math.floor(Math.random() * (max - min + 1) + min) + file.originalname)
    }
})

const upload = multer({ storage: storage })

app.post('/makepost', upload.array('gallery'), (req, res) => {
    const files = req.files;
    const header = req.body.header;
    const post = req.body.post;

    const makePostSql = "INSERT INTO posts (header, post) VALUES ?";
    const postValues = [[header, post]];

    con.query(makePostSql, [postValues], (err, postResult) => {
        if (err) {
            console.log('Error creating post:', err);
        }

        con.query("SELECT id FROM posts ORDER BY id DESC LIMIT 1", (request, result) => {
            if (result) {
                const lastPostId = result[0].id.toString();
                const galleryValues = files.map(fileName => [lastPostId, fileName.filename]);
                if (galleryValues.length > 0) {
                    const makeGallerySql = "INSERT INTO gallery (postid, name) VALUES ?";
                    con.query(makeGallerySql, [galleryValues], (err, galleryResult) => {
                        if (err) {
                            console.log('Error inserting into gallery:', err);
                        }
                    });
                } else {
                    console.log("No files to insert into the gallery.");
                }
            } else {
                console.log("No posts found.");
            }
        });
    });
});

app.get('/postsapi', (req, res) => {
    con.query("SELECT * FROM posts ORDER BY id DESC", (request, result) => {
        res.send(result)
    })
})

app.get('/galleryapi', (req, res) => {
    con.query("SELECT * FROM gallery", (request, result) => {
        res.send(result)
    })
})

app.post('/deletepost', upload.none(), (req, res) => {
    const { id } = req.body
    const deletepostsql = "DELETE FROM posts WHERE id = ?"
    con.query(deletepostsql, [id], (err, result) => {
        if (err) {
            console.log(err)
        }
        const getFilesNamessql = "SELECT name FROM gallery WHERE postid = ?"
        con.query(getFilesNamessql, [id], (err, result) => {
            if (err) {
                // Handle the error
                console.error(err);
                return;
            }

            result.forEach(element => {
                const fileName = element.name;

                fs.access(`../client/public/gallery/${fileName}`, fs.constants.F_OK, (accessErr) => {
                    if (!accessErr) {
                        fs.unlink(`../client/public/gallery/${fileName}`, (unlinkErr) => {
                            if (unlinkErr) {
                                console.error(`Error unlinking file ${fileName}:`, unlinkErr);
                            }
                        });
                    } else {
                        console.error(`Error accessing file ${fileName}:`, accessErr);
                    }
                    const deleteGallerySql = "DELETE FROM gallery WHERE postid = ?"
                    con.query(deleteGallerySql, [id], (err, result) => {
                        if (err) {
                            console.log(err)
                        }
                    })
                });
            });
        });
    })
})

app.post('/sendmessage', upload.none(), (req, res) => {
    const header = req.body.header
    const message = req.body.message
    const makeMessageSql = "INSERT INTO messages (header, message) VALUES ?"
    const messageValues = [[header, message]]
    con.query(makeMessageSql, [messageValues], (err, result) => {
        if (err) {
            console.log(err)
        }
    })
})

app.get('/messagesapi', (req, res) => {
    con.query("SELECT * FROM messages ORDER BY id DESC", (request, result) => {
        res.send(result)
    })
})

app.listen(port)

rqcrx0a6

rqcrx0a61#

我认为你有一个竞争条件。看起来你试图用axios.post("http://localhost:3001/makepost"改变一些东西,然后你立即尝试用axios.get("http://localhost:3001/postsapi")获取改变的结果,而没有等待第一个帖子的响应。也许第二个两个axios.get调用应该在第一个axios.post.then处理程序中。
问题存在于MakePostDeletePost函数中。

Bad:竞态条件

axios.post("http://localhost:3001/deletepost", formData).then(response => {
            if (response.data) {
                console.log(response.data)
            }
        }).catch(err => console.log(err))
        axios.get("http://localhost:3001/postsapi").then(response => {
            setPosts(response.data)
        }).catch(err => console.log(err))
        axios.get("http://localhost:3001/galleryapi").then(response => {
            setGallery(response.data)
        }).catch(err => console.log(err))

字符串

Good:等待确认post已完成

axios.post("http://localhost:3001/deletepost", formData).then(response => {
            if (response.data) {
                console.log(response.data)
            }
            axios.get("http://localhost:3001/postsapi").then(response => {
                setPosts(response.data)
            }).catch(err => console.log(err))
            axios.get("http://localhost:3001/galleryapi").then(response => {
                setGallery(response.data)
            }).catch(err => console.log(err))
        }).catch(err => console.log(err))

另外,您必须发送响应

此外,makepostdeletepost API端点的app.post不会发送响应(你完全忽略了res)。你错过了像res.sendStatus(200);这样的东西,它会回复浏览器操作已经完成,允许您等待,直到发出依赖于makepostdeletepost操作已完成的后续请求。

相关问题