Ajax POST with jQuery and Node.js Express always returning 404: Not Found

Asked

Viewed 1,056 times

4

I created the route below to accept POST requests, but calls via AJAX to this route are always returning error 404: Not Found.

/* Arquivo: integracoes.js */
var express = require('express');
var router = express.Router();

// Esta rota funciona e não dá erro: http://localhost:3001/integracoes/consultas
router.get('/consultas', function(req, res, next) {
    res.render('consultas');
});

// 404: Not Found quando chamado pela requisição Ajax descrita mais à frente nessa pergunta.
router.post('/consulta/statuspedido', function(req, res) {
    var statusDoPedido = 10;

    res.send(JSON.stringify({statuspedido: statuspedido})); 
});

module.exports = router;

In app.js I use this definition of routes as follows:

var integracoes = require('./routes/integracoes');
app.use('/integracoes', integracoes);

On the HTML page I am using the following called Ajax:

$.ajax({
    url: '/consulta/statuspedido',
    contentType: 'application/json',
    type: 'POST',
    success: function(data) {
        debugger;

        textAreaDeResposta.val(imprimaCamposDoObjeto(data));
    },
    error: function(){
        textAreaDeResposta.val('Ocorreu um erro ao tentar consultar o status do pedido.');
    }
});

In the Browser the answer I get is the following:

http://localhost:3001/query/status 404 (Not Found)

The site is configured to run on port 3001, and all other routes of the site (GET) are working. The only one that doesn’t work is the one I’m trying to access via AJAX.

Why URL not found?

1 answer

3


The express.Router() has to be used as middleware. In your example you are correctly defining a "route" but you are not calling it middleware. You have to pass it to app and with a "route" too, from which the other is relative.

So you’re missing something like this:

app.use('/', router);
// ou
app.use('/consulta', router); // e no router "router.post('/statuspedido', ..."
// ou ainda
app.use('/consulta/statuspedido', router); // e no router "router.post('/', ..."

The concept of "route" brought something new to the express, relative paths. In the same way that in a browser we can point an image to only imagem.png and not pasta/subpasta/imagens/imagem.png, router looks something like this. So when you use

app.use('/integracoes', router);

the router doesn’t know you’re already inside a subfolder, that information is irrelevant to you.

So other paths that are drawn within it in addition to the initial path. As in the 3 examples I had initially put. In practice for your code the starting point is /integracoes then what you leave on the router will be on top of that.

The final path to which ajax should point is then

/integracoes/consulta/statuspedido

Browser other questions tagged

You are not signed in. Login or sign up in order to post.