Home > front end >  axios returns 404 on first post request
axios returns 404 on first post request

Time:09-09

 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?

CodePudding user response:

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.

CodePudding user response:

From your error image, the post request needs materia as slug but you are not sending it in the first request..

In your First Api call, you are just calling

http://localhost:3001/getNotasAluno/

Instead it should be

http://localhost:3001/getNotasAluno/1

1 is the materiaId

  • Related