参考了网上的资料,自己开始实践。
1.在命令行视图下创建自己的工程目录:
D:\Develop\nodejs>express MyPrj
2.进入工程目录,下载express所需的依赖项:
cd MyPrj
npm install
3.下载完毕后,即可启动express应用:
npm start //或者 node app.js,app.js 为express自动生成的js文件
4.在浏览器中输入 http://localhost:3000/ 或 http://localhost:3000/users ,浏览器都会有相应显示信息。
5.写自己的服务程序:
在先前创建的MyPrj目录下,创建一个 server.js 文件,编辑文件内容如下:
var express = require(‘express’); // 用来引入express模块 ‘express’
var app = express(); // 创建express 实例对象
app.set(‘port’, process.env.PORT || 3000); // 设置端口为3000
// 设置首页的路由 用 ‘/’ 表示
app.get(‘/’,function (req,res) { res.send(‘Welcome first page’) });
// 设置about页面的路由 用 ‘/about’ 表示
app.get(‘/about’,function (req,res) { res.send(‘The about page’) });
// 设置404页面
app.use(function (req,res,next) { res.status(404); res.send(‘404 - Not found’) });
// 监听端口如果有用户进入页面发送请求我们输出以下语句
app.listen(app.get(‘port’),function () { console.log(‘express started on port 3000’) });
6.在命令行中停掉当前的应用,启动自己新创建的应用:
node server.js
7.再次在浏览器中输入 http://localhost:3000/ 或 http://localhost:3000/users ,浏览器会显示自己想要显示的信息。