1

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 . https://nodejs.org/docs/latest/api/fs.html – Gary Apr 10 '19 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 Apr 10 '19 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 Apr 10 '19 at 20:36
  • That’s possible, of course. All depending on your individual configuration – Nico Haase Apr 10 '19 at 20:40

1 Answers1

1

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

LJD
  • 498
  • 4
  • 11