0

I'm trying to learn ExpressJS and NodeJS to use with the Twitter API. This is my setup so far:

package.json

{
  "name": "twitter-express",
  "version": "1.0.0",
  "description": "",
  "main": "server.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "dependencies": {
    "express": "^4.16.3",
    "hogan-express": "^0.5.2",
    "twit": "^2.2.9"
  }
}

server.js

var express = require('express');
var server = express();

server.set('port', process.env.PORT || 3003);
server.engine('html', require('hogan-express'));
server.set('view engine', 'html');

server.get('/', function(req, res) {
   res.render('index', {title: 'Twitter', data: theTweets});
});

server.listen(server.get('port'), function() {
   console.log('Listening on port:' + server.get('port'));
});

var Twit = require('twit');
var theTweets = [];

var T = new Twit({
   consumer_key: '',
   consumer_secret: '',
   access_token: '',
   access_token_secret: ''
});

var params = {
   q: '#nodejs',
   count: 10,
   result_type: 'recent',
   lang: 'en'
}

T.get('search/tweets', params, getData);

function getData(err, data, response) {
   var tweets = data.statuses;
   for (var i = 0; i < tweets.length; i++) {
      theTweets.push(tweets[i].text);
   }
 }

I'm using hogan-express as template engine as I followed a tutorial. With this setup everything works and the tweets are displayed on the webpage. However, as I'm trying to learn this I have some questions about Express and Node:

If I've understand correctly, I need to use Express to serve the client side of my application (to display tweets on a webpage), is this the best way for a Node application or can I do it in some other way?

Do I have to use a template engine or can I use it just with html? In that case, how can I use it without a template engine? Thank you.

3
  • 1
    You don't have to use a template engine at all really. You could write your application using anything you want, and merely serve the files via your Node Express application. This gives you the freedom to leverage whatever tech-stack you wish for the UI. Think of it this way... Express is merely handling the majority of the low-level operations that you would normally have to code by hand. It then allows you to expose a RESTful API for your application to use. example Commented May 2, 2018 at 12:56
  • Yes, that is exactly what I want, so that I can use a js framework or similiar if I wish. But I can't find any good explanations in how to do it. I'm not asking for a solution, I just really want to learn this. I'm afraid the example confuse me a bit, using polymer, which I've never used. Commented May 2, 2018 at 13:08
  • Here is an example similar to what you are currently doing: scotch.io/@devGson/… Commented May 2, 2018 at 13:34

3 Answers 3

1

Node, Express and hogan are solving different problems here.

NodeJS is an open-source server side runtime environment built on Chrome's V8 JavaScript engine. It has its own pros and cons but for the sake of simplicity you can consider it as a server which have many built in modules to interact with network cards, to understand http etc.
Express is a framework for developing web applications. Frameworks are just opposite of libraries. Think of frameworks like structures which have basic wiring done and you just need to put your code/handlers at required places, and the framework will call your code/handler whenever needed. Framework makes the work easy by doing all the side jobs so that you can focus on actual problem that you are solving. You can do the things without express too, or say without any other framework but now you have to deal with a lot of things.
For example, now you need to parse the http headers yourself, check the url, check the method type, parse the query params, then call appropriate handler to handle that particular request. Now as you can see feel that these all things are overhead and not the actual problem that you wish to solve. When using express, you get a router which takes care of all these things and call the handler that you define for a particular request. So, express is making your development faster and easier. There are many other frameworks too, like hapi, sails etc that do more or less same things.
Hogan is a templating engine. Template engine makes your work easier in rendering the webpage. For example you can use conditionals, loops etc in your template engine only, that otherwise you need to handle using javascript. For example just consider that number of menu items on your page is not fixed, then how will you handle it ? Either you will create the html on the fly on server side only, for which you will use loops given by template engine, or you will serve the basic html and use javascript (jquery, angular etc) to update the menu.

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you for the detailed explanation, that cleared some confusions!
0

Exactly as you can observe Express(Node js framework) allow you to build a backend application or service. On client side you can fetch the API or data using Angular , Jquery or Pure Javascript. pug or Jade should be just fine as a templace engine.

5 Comments

But if my goal is to use NodeJS, I have to use Express? Because when I tried to use NodeJS without Express, I was unable to display the results in the browser.
Yes, you can do it but it is going to be a long run, expressjs is framework that allow you to simplify the development of your backend server. as I said it before, Node can still run, you can use Javascript on your html to load data coming Node Web Api.
Ok, do you know any good example that explains how to do this? When I'm searching for it, I can only find examples that displays the result in the terminal and not in the browser.
You simply perform an AJAX/XHR/Fetch request to your API created in the node application. Fetch
I found a suitable soltion for Express, Node js and Jquery( Javascript Nodes and HTML
0

I found a suitable soltion for Express, Node js and Jquery( Javascript Nodes and HTML

<!DOCTYPE html>

            <head>
                <meta http-equiv="content-type" content="text/html; charset=UTF-8"/>
                <script type="text/javascript" src="jquery.min.js"></script>
                <script type="text/javascript">
                    $(document).ready(function() {
                        $.ajax({
                            type: "GET",
                            data: '{}',
                            contentType: "application/json; charset=utf-8",
                            url: "urlofyourserver:3000/path/",
                            dataType: "jsonp",
                            processdata: true,
                            success: function(data) {
                                $('#htmldiv').html(data);
                            }
                        });

                    });


            </script>
        </head>
        <body>
            <div class="mylist" id="htmldiv"></div>
        </body>
    </html>

1 Comment

Thanks, however I don't want to use jquery, just plain js. But thanks anyway!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.