Express and Node.js Training from StrongLoop

该文件可能是相对于英文的文档已经过时。有关最新更新,请以英文的文档

This document might be outdated relative to the documentation in English. For the latest updates, please refer the documentation in English.

Hello world 实例

下面展示的就是一个基本的 Express 应用实例。

var express = require('express')
var app = express()

app.get('/', function (req, res) {
  res.send('Hello World!')
})

var server = app.listen(3000, function () {

  var host = server.address().address
  var port = server.address().port

  console.log('Example app listening at http://%s:%s', host, port)

})

The req (request) and res (response) are the exact same objects that Node provides, so you can invoke req.pipe(), req.on('data', callback) and anything else you would do without Express involved.

The app starts a server and listens on port 3000 for connection. It will respond with “Hello World!” for requests to the homepage. For every other path, it will respond with a 404 Not Found.

Save the code in a file named app.js and run it with the following command.

$ node app.js

Then, load http://localhost:3000/ in a browser to see the output.