English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

NodeJS Basic Tutorial

NodeJS Express.js

NodeJS Buffer & URL;

NodeJS MySql

NodeJS MongoDB

NodeJS File (FS)

Other NodeJS

Installazione di Express.js

Express is a simple and flexible node.js Web application framework, providing a series of powerful features to help you create various Web applications and rich HTTP tools.
Express can be used to quickly build a full-featured website.
Core features of Express framework:

  • Middleware can be set to respond to HTTP requests.

  • Defined route tables for executing different HTTP request actions.

  • HTML pages can be dynamically rendered by passing parameters to the template.

Install Express

Install Express and save it to the dependency list:

$ cnpm install express --save

The above commands will install the Express framework in the node_modules directory of the current directory, and an express directory will be automatically created under node_modules. The following important modules need to be installed with the Express framework:

  • body-parser - middleware in node.js used to handle JSON, Raw, Text and URL encoded data.

  • cookie-parser - this is a tool for parsing cookies. Cookies passed can be retrieved using req.cookies and converted to an object.

  • multer - middleware in node.js, used to handle form data with enctype="multipart/form-data" (sets the MIME encoding of the form).

$ cnpm install body-parser --save
$ cnpm install cookie-parser --save
$ cnpm install multer --save

Dopo l'installazione, possiamo verificare la versione utilizzata di express:

$ cnpm list express
/data/www/node
└── [email protected]  ->  /Users/tianqixin/www/node/node_modules/.4.15.2@express

Primo esempio di framework Express

Prossimamente utilizzeremo il framework Express per esportare "Ciao Mondo".

Nell'esempio seguente, abbiamo importato il modulo express e risposto con la stringa "Ciao Mondo" dopo che il client ha inizializzato la richiesta.

Crea il file express_demo.js con il seguente codice:

Codice del file express_demo.js:
//file express_demo.js
var express = require('express');
var app = express();
 
app.get('/', function (req, res) {
   res.send('Ciao Mondo');
)
 
var server = app.listen(8081, function () {
 
  var host = server.address().address
  var port = server.address().port
 
  console.log("Esempio di applicazione, indirizzo di accesso http://%s:%s", host, port)
 
)

Esegui il seguente codice:

$ node express_demo.js 
Esempio di applicazione, indirizzo di accesso http://0.0.0.0:8081

Accedi al browser tramite http://127.0.0.1:8081, i risultati sono i seguenti:

Ciao Mondo