top of page
Search
  • Writer's picturealeksvp

How to set a simple HTTP server with routes using Node and Express

Full code: https://github.com/aleksvp2017/simpleserver

Using:

  • Node.js;

  • Express.


Assuming that you have Node instaled (if you don't, you can download and follow the steps here), the first steps are to create the package.json and install express:

  • npm init

  • npm i express

Also, install nodemon (for hot deploy purposes): npm i nodemon.


The entry point is going to be app.js:

var express = require('express') var app = express() //so we can read request data app.use(express.urlencoded({ extended: true})) app.use(express.json()) //you can set and environment variable and use process.env.PORT instead var port = 3001 app.listen(port, () => { console.log('Server up and listening at ' + port)}) To start the server, on the terminal: nodemon app.js


From this point, your HTTP server is up and running.


The next step is to create the routes, which is an array with information that allow you to match an HTTP request with who has to deal with it, a function in a js file, for instance. Going to put it in a separate file, route.js:

const Product = require('./product.js') var routes = [ { uri: '/products', httpmethod: 'get', component: Product, method: 'list'}, ]; module.exports = { routes }


This way, Product.list is going to be called in response for <<server_address>>/products.


Product is just a fake service:

const list = async function (req, res, next){ res.status(200).json({ products: [ { id: 1, name: 'product1' }, { id: 2, name: 'product2' }, ] },) } module.exports = { list }


Finally, back on app.js you have to tell express to use the routes, like this:

var Routes = require('./routes.js') Routes.routes.map(route => { app[route.httpmethod](route.uri, route.component[route.method]) })


To test, just access http://localhost:3001/products. It should return the json with products one and two.


Not that complicated, right?








23 views0 comments

Comments


Post: Blog2_Post
bottom of page