Dieses Blog durchsuchen

Samstag, 20. August 2016

node.js: create your first express webserver

In the last tutorial, we have created a simple webserver. That was great as preperation to use the expressframework, which can handle the webserverstuff for us. Let's have a look to express.

Prerequisits

node.js installed
npm installed

Install express globaly

$ npm install -g express

Create a npm project

Create your project rootfolder "express-project" and open a terminal in that folder and typpe:
$ npm init

Follow the intstructions on your terminal.

Add needed dependencies

Open package.json and add your dependencies. My package.json looks like that:
{
"name": "simple-express",
"version": "1.0.0",
"description": "simple exress sample",
"main": "app.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"keywords": [
"exptress"
],
"author": "peboethig",
"license": "MIT",
"dependencies":
{
"node-mailer":"*",
"body-parser":"*",
"express":"*",
"jade":"*"
}
}
view raw package hosted with ❤ by GitHub

You can just pick the "dependencies" object 

 

Add you dependencies

Create a file "app.js" and paste following code
var express = require("express");
var path = require("path");
var bodyParser = require("body-parser");
var nodeMailer = require("'nodemailer");
var app = express();
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended:false}));
app.get("/", function(req, res) {
console.log("hello world");
res.send("hello world");
});
app.listen(3000, function() {
console.log("App listening on port 3000!");
});
view raw app.json hosted with ❤ by GitHub
This will reference your dependencies and setup your express webserver.
As you can see, the webserver will be bound on port 3000 and it will return a simple "Hello world" response and will log the same words to the console.

Start the webserver

Open a terminal in the projectroot and type:
$ node app.js 


Now you can surf http://localhost:3000 and you should see "Hello world"

Thats it

Keine Kommentare:

Kommentar veröffentlichen