axios returns 404 on first post request

Issue

     function verNotasAluno(e) {
        e.preventDefault()
        setMateria(String(responseProfessor[1]))
        axios
            .post(`http://localhost:3001/getNotasAluno/${materia}`, { lupaAluno })
            .then((response) => {
                if (response.data === 'Erro') {
                    alert('Aluno não encontrado')
                } else {
                    setNotasResponse(JSON.stringify(response.data))
                }
            })
    }
    
    return (
        <div>
            <form onSubmit={verNotasAluno}>
                <span>Nome:</span> <input type={'text'} onChange={(e) => { setLupaAluno(e.target.value) }} required /> <br />
                <br />
                <button>Buscar Nota</button>
            </form>
        </div>
    )

Server Side:

    app.post('/getNotasAluno/:materia', (req, res) => {
        const nome = req.body.lupaAluno
        const materia = req.params.materia
    
        let searchquery = ''
        if (materia === 'Fisica') {
            searchquery = 'SELECT nota_fisica, nota_fisica2, nota_fisica3 FROM pessoas where nome = ?;'
        } else if (materia === 'Portugues') {
            searchquery = 'SELECT portugues, portugues2, portugues3 FROM pessoas where nome = ?;'
        } else if (materia === 'Matematica') {
            searchquery = 'SELECT matematica, matematica2, matematica3 FROM pessoas where nome = ?;'
        }
        db.query(searchquery, nome, (err, result) => {
            if (result.length === 0) {
                res.send('Erro')
            } else {
                res.send(result)
            }
        })
    })

As I said in the title, the first time I make a request submitting the form, it gives this error: Click to see the image error but if I make another request after the first one, it works normally

I’m a beginner, can someone shed some light on me please?

Solution

i found out what was going wrong, the ‘materia’ parameter was going empty to the server, that’s why the first request gave 404. Had to use UseEffect to update useState or something. Thanks to anyone who saw this code.

Answered By – Light

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published