1

I have this in jQuery :

$.ajax(
    {
        type: 'POST',
        data : mydata,
        url : '/routerfunction',
        dataType : 'String',
        success : function(data)
        {
            //do stuff

        },
        error: function(xhr, status, error)
        {
            console.log(error);
            console.log(xhr);
            console.log(status);
        },


    }

And I have this in index.js(node)

router.post('/routerfunction/:mydata', function(req,res)
{
    //do stuff
}

And I have this in app.js(node)

app.use('/', index);
app.use('/users', users);

When I do a POST request to routerfunction, I get 404 error. I have really tried to find the bug but I couldn't.. Where could the bug be? Thanks in advance.

jason
  • 6,962
  • 36
  • 117
  • 198
  • 1
    I'm non intimately familiar with node, but `'/routerfunction/:mydata'` makes it seem like you are expecting the data to be on the url. Which is not how POST requests are. The data is in the request body. – Taplar Jul 24 '17 at 15:00
  • 1
    It miss in your ajax url something after routerfunction, your node is waiting smth like /routerfunction/data as url – Cylexx Jul 24 '17 at 15:02

1 Answers1

1

This route:

router.post('/routerfunction/:mydata', ...

needs a URL like:

/routerfunction/SOMETHING

and will not match:

/routerfunction

so the 404 is correct here.

You would need:

router.post('/routerfunction', ...

to match that request.

Keep in mind that you also need a body-parser to parse the body which will include the data sent in the AJAX request which you will then be able to access with req.body - see those answers for some examples of that:

rsp
  • 107,747
  • 29
  • 201
  • 177