404 when making a request to express route 404 when making a request to express route express express

404 when making a request to express route


Use following code. Use ajax instead of fetch and method must be POST. Fetch is not working as it is get request by default.

Option 1

    $.ajax({       method: "POST",       url: "/list"      })     .done(function( msg ) {      alert( "Data " + msg );  });

Option 2Change only following code => POST to GET

app.get('/list', (request, response) => {  //get data then...  response.send(data)});

Option 3Use POST in fetch

fetch("/list",{    method: "POST"}).then(function(data){  alert( "Data " + data ); })

Thanks to @vesse for suggesting option 3

https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch


My web server (Apache / Ubuntu) is set up to serve html out of the public_html directory by default. Does that mean my whole node app structure needs to be moved into the public_html folder and the actual html moved into a static folder or something?

Node.js and Apache can use the same static folder without conflict, but they both cannot listen on the same port. It is likely your Apache server is already running on port 80. If your Node.js server runs on port 3000, requests to port 80 will not match routes you write in your app and thus 404 will return (unless of course you had the same routes in a separate Apache hosted application).

What about the port? The node app listens on port 3000 - but I'm not sure how (or if) to make a request to that port specifically.

Since Apache is probably already listening on port 80, any request you send to http://localhost will hit your Apache server. Instead, you must make requests that include a port number, http://localhost:3000 will hit your Node.js server.

Route path - I am posting to /list but should it be ../list?

No, you should post to /list and also regard all the points Rakesh made in his answer so that you correctly match POST to POST from client to server or switch to GET if that's more appropriate. As in the second point, be sure you are posting to http://localhost:3000 and not just http://localhost. As you pointed out, one is Apache and the other is Node.js

Finally, here's the static server line of code I use when serving from a folder that is adjacent to my app script:

app.use('/', express.static(__dirname + '/public_html'));

With this, all files you put in the public_html folder become navigable in your application, which includes everything Apache related as well. Note __dirname is the always the directory from which the currently executing script is run. To visit this site, simply go to http://localhost:3000 in your browser and you should see your index file.