使用Express的两种方法

使用Express的两种方法


        最近过年,放假给自己冲了下电,学了一点点Node.js的知识,以后吹水可以用到嘛。

        如果我写的不足以让你理解,你可以访问以下地址,查看官方文档,自己动手,丰衣足食

        官网地址:http://www.expressjs.com.cn/

        介绍一下Express,直接上图吧

使用Express的两种方法_第1张图片

        其实就是个Nodejs的框架,极简、灵活、可定制的内在含义代表着它不适合懒人,它只提供一些“套路化”的代码,至于要什么功能,就得自己去找去添加了。

        使用Express的第一种方法:

在项目文件夹test目录中,命令行运行

npm install express -save

这个命令会生成一个node_modulesExpress就在里面。


然后我们再在test目录中创建test.js测试文件,文件代码如下

var express = require('express');

var app = express();
app.set('port',3000);

app.get('/',function(request,response){
    response.type('text/plain');
    response.send('予怀之言的博客');
})
//订制404页面
app.use(function(request,response){
    response.type('text/plain');
    response.status(404);
    response.send('404 Not Found');
    
})

//订制500页面
app.use(function(err,request,response,next){
    console.error(err.stack);
    response.type('text/plain');
    response.status(500);
    response.send('500 Server Error');
})

app.listen(app.get('port'),function(){
    console.log('Express is started on http://localhost:'+app.get('port')+';press Ctrl+C to stop');
});


在命令行中执行

node test.js

        接着访问http://localhost:3000/

        出现“予怀之言的博客”成功

 

        使用Express的第二种方法:

        直接使用Express生成器,通过应用生成器工具 express 可以快速创建一个应用的骨架

通过以下命令安装

npm install express-generator –g

然后直接用express命令生成框架

使用Express的两种方法_第2张图片


        接着访问http://localhost:3000/

        你会知道你成功了













你可能感兴趣的:(Node.js,Javascript)