jason jason - 3 years ago 52
Javascript Question

Post request to Node returns 404

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.

rsp rsp
Answer Source

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:

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download