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

4

I created the route below to accept POST requests, but calls via AJAX for 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 make use of this route definition as follows:

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

In the HTML page I'm using the following Ajax call:

$.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 response I get is as follows:

link 404 (Not Found)

The site is configured to run on port 3001, and all other site (GET) routes are running. The only one that does not work is the one I'm trying to access via AJAX.

Why is the URL not found?

    
asked by anonymous 08.10.2015 / 02:16

1 answer

3

The express.Router() must be used as middleware. In your example you are setting up a route correctly but you are not calling it middleware. You need to pass it to app and 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 express , that of relative paths. Just as in a browser we can point an image to only imagem.png and not pasta/subpasta/imagens/imagem.png , the router is more or less like this. So when you use

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

router does not know you're already in a subfolder, that information is irrelevant to you.

So other paths that are defined within it add to the initial path. Like the 3 examples I had initially put. In practice for your code the starting point is /integracoes so what you define on the router will be on top of that.

The final path that ajax should point to is

/integracoes/consulta/statuspedido
    
08.10.2015 / 08:56