Gabriel Cretu
Gabriel Cretu

Reputation: 57

How to create routes in node.js and include html code

I am coming back here with some issues regarding Node.Js. I am kind of new to Node, and I am trying to write some code to create a server and then, create some routes between pages.

In order to create the routes, do I have to convert the html file to hbs?

So basically, instead of the html tags, is there any possibility to include html pages, or files?

Also, for the CSS, do I need to do something or it should be included automatically?

I think that, in order to create a route between the pages, I need to check the URL?

Do I need separate file in which I am supposed to create some code for GET and POST methods? I am not really sure.

If I am using WebStorm and create a Node.Js Express project, it creates an folder 'bin' in which there is a file 'www'. What is this file?

Kind Regards, G

//code for the server:

var http = require('http');
const express = require('express')
const app = express()
const port = 3000

http.createServer(function (req, res) {
    res.writeHead(200, { 'Content-Type': 'text/html' }); // http header
    var url = req.url;

    if (url === '/'){
        res.write(`<h1>home page</h1>`); //write a response
        res.end(); //end the response
    } else if (url === '/index') {
        res.write('<h1>index page<h1>'); //write a response
        res.end(); //end the response
    } else if (url === '/test') {
        res.write('<h1>test page<h1>'); //write a response
        res.end(); //end the response
    } else if (url ==='/contact'){
        res.write('<h1>contact page<h1>'); //write a response
        res.end(); //end the response
    } else if (url ==='/about'){
        res.write('<h1>about page</h1>'); // write a response
        res.end(); //end the response
    }
}).listen(port, function () {
    console.log(`server start at portL ${port}`); //the server object listens on port 3000
}); 

Upvotes: 3

Views: 2066

Answers (1)

Diogo Capela
Diogo Capela

Reputation: 6600

I feel that what you need is a rendering engine. You can use the hbs npm module, which is a small and easy-to-use view engine based on handlebars.js.

You need first to install hbs.

$ npm install hbs --save

Then make sure your folder structure is something like this:

├── package-lock.json
├── package.json
├── server.js
└── views
    ├── about.hbs
    ├── contact.hbs
    └── home.hbs

And your server.js file, like this:

const path = require('path')
const express = require('express')
const hbs = require('hbs')

const app = express()
const port = 3000

// Configure view engine and set views folder

app.set('view engine', 'hbs')
app.set('views', path.join(__dirname, 'views'))

// Manage the routes

app.get('/', (req, res) => {
    res.render('home')
})

app.get('/about', (req, res) => {
    res.render('about')
})

app.get('/contact', (req, res) => {
    res.render('contact')
})

// Start the server

app.listen(port, () => {
    console.log(`The server is running on port ${port}.`)
})

This way, using the hbs view engine, you could also pass data from the server to your HTML content, like this:

app.get('/about', (req, res) => {
    const data = { name: 'John Doe' }
    res.render('about', data)
})

And following this example you would catch the data sent from the server at your /views/about.hbs file, with something like this:

<div>
    <h1>Hello, {{name}} how are you today?</h1>
</div>

Hope this helps you.

EDIT:

To reference CSS files you must create a static directory at your Node.js server. To do it add this to your server.js file:

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

Then make sure you create a /public folder and move your assets there, something like this:

├── server.js
└── public
    ├── bundle.css
    └── logo.png

After that, you can now reference all your static content from your views. For example in your home.hbs:

<!-- Reference static CSS files -->
<link href="/public/bundle.css" rel="stylesheet">

<!-- Reference static images -->
<img src="/public/logo.png" alt="" />

If you don't want to use a view engine and just want to render a plain HTML file you can also do it:

app.get('/contact', (req, res) => {
    res.sendFile(path.join(__dirname + '/views/contact.html'));
});

Upvotes: 1

Related Questions