The answer for Node.js - How to send data from html to express solves the problem I have by using a different port for the server. I was wondering how live websites for example this website (stackoverflow's search bar) use a form action that is a directory ("/search") instead of a port similar to the answer at the link? Is node.js incapable of listening to a directory or am I ignorant when it comes to how http requests work?
-
Try fs.watch and send event data using websockets or next page refresh to /search . nodejs.org/docs/latest/api/fs.htmlGary– Gary2019-04-10 20:20:03 +00:00Commented Apr 10, 2019 at 20:20
-
I don't really understand your question: what's the problem in sending data from the browser to any server, and handle whatever the server sends as a response?Nico Haase– Nico Haase2019-04-10 20:20:33 +00:00Commented Apr 10, 2019 at 20:20
-
@NicoHaase My question is if I had a html page served at 127.0.0.1:8000 is it possible to submit a form to 127.0.0.1:8000/search or would I have to choose a different port so my node.js server could listen to the request.Hatergenerator– Hatergenerator2019-04-10 20:36:49 +00:00Commented Apr 10, 2019 at 20:36
-
That’s possible, of course. All depending on your individual configurationNico Haase– Nico Haase2019-04-10 20:40:48 +00:00Commented Apr 10, 2019 at 20:40
1 Answer
You listen on a port for http requests. Your front end will do an ajax(asynchronous javascript and xml) request in your javascript code to a route on your server through a port.
If you want a good tool for making easy ajax requests, you can use jQuery, or Axios, and look up how to do ajax with those libraries.
On the back end your server is listening to a port for requests to routes. Set up a route(what you've called a directory) to respond to requests to a particular URL. The example you mentioned showed:
app.post('/myaction', function(req, res) {
res.send('You sent the name "' + req.body.name + '".');
});
Express is a backend framework for doing all kinds of things, but most commonly, handling HTTP requests and rendering HTML. So on the front end when you make your ajax request to /myaction, you can respond like this:
app.post('/myaction', function(req, res) {
res.render('templateFileToRender', { dataToDynamicallyTurnIntoHTML: data } );
});
Express will render your template file, then send the HTML to your front end, and you will update your frontend div or whatever with the rendered HTML.
If you want more info please leave a comment