美文网首页
Express学习 - hello world

Express学习 - hello world

作者: _palm | 来源:发表于2016-10-23 22:48 被阅读88次

express : 官网描述,express是一个基于Node.js的快速的、简洁的、灵活的web 框架。 有点像java 之于servlet , 它一般和html模板结合使用,动态输出信息到客户端。

hello world
新建一个项目目录,然后将express框架支持包加入到这个项目中,在Node.js中安装第三方包默认都是基于本地项目的,这和添加第三方jar到java web项目lib很接近,当然在Node.js中也可以将指定包作为全局使用,安装命令:

npm install express

这样express包将被下载到当前的node_modules目录下,该目录下有不仅仅express包:

accepts              escape-html        methods         range-parser
array-flatten        etag               mime            send
content-disposition  express            mime-db         serve-static
content-type         finalhandler       mime-types      setprototypeof
cookie               forwarded          ms              statuses
cookie-signature     fresh              negotiator      type-is
debug                http-errors        on-finished     unpipe
depd                 inherits           parseurl        utils-merge
destroy              ipaddr.js          path-to-regexp  vary
ee-first             media-typer        proxy-addr
encodeurl            merge-descriptors  qs

这样,就可以开始使用express了。
在项目根目录新建文件app.js ,按照惯例,跟着官网入门编写一个hello,world

var express = require('express') ;
var app = express() ; //得到express实例,类似 new express()

app.get('/',function(req,res) {
    res.send('hello world!') ;
}) ;

var server = app.listen(8081,function() {
    var host = server.address().address ;
    var port = server.address().port ;
    console.log('server has started at http:// %s:%s', host,port) ; 
}) ;

这段代码有点像之前学习Node.js基础的时候第一个栗子:

var http = require('http') ;
var server = http.createServer(function(req,res) {
    res.writeHead(200,{'Content-Type':'text/plain'}) ;
    res.write('Hello,World!') ;
    res.end() ;
}).listen(8081) ;

使用express后,不再需要自己造轮子,创建一个server了。我们只需要尽可能的关注业务就可以了。

运行 node app.js 访问http://localhost:8081/就可以看到页面输出hello world! ,如果访问其他路径如http://localhost:8081/start 就会告诉找不到这个路径/start
如果使用我们自己的轮子,由于没有做路由,所以所有请求都会输出同一个信息 -- hello world 。所以,express在这个栗子中,已经帮我们做了简单的路由处理。

END

学习参考在这里/

相关文章

  • Express学习 - hello world

    express : 官网描述,express是一个基于Node.js的快速的、简洁的、灵活的web 框架。 有点像...

  • Express学习 - 路由

    在Express学习 - hello world,知道了Express是在Node.js的基础之上对Node.js...

  • express实现Hello World!

    express是基于node.js 的web应用程序框架,为web和移动应用开发提供一组强大的功能。 安装 在安装...

  • 13 - express

    Express 基于 Node.js 平台,快速、开放、极简的 Web 开发框架 。 Hello World Re...

  • 常用markdown语法

    Hello World! Hello World! Hello World! Hello World! Hello...

  • hello

    hello, world hello, world hello, world hello, world

  • Markdown

    标题: hello world hello world hello world hello world hello...

  • 2018-06-11

    markdown hello world hello world hello world hello world ...

  • hello world

    Express 是node.js应用最广的web框架。建一个hello world mkdir lesson1 &...

  • Express框架初探

    本文主要内容有五点: 1. 安装; 2. Hello World; 3. 使用express-generator快...

网友评论

      本文标题:Express学习 - hello world

      本文链接:https://www.haomeiwen.com/subject/vfbkuttx.html