Express学习笔记

express是基于nodejs的web开发框架,既可以快速的搭建网站,也可以创建api接口。

1、创建package.json

在项目目录下,可以通过npm init命令创建。

{
  "name": "hello-world",
  "description": "hello world test app",
  "version": "0.0.1",
  "private": true,
  "dependencies": {
    "express": "4.x"
  }
}

主要是其中的dependencies属性,指定了express。

在该文件夹下运行 npm install 即可以安装express框架了。

2、创建服务端文件

var express = require('express');
var app = express();
app.get('/', function (req, res) {
  res.send('Hello world!');
});
app.listen(3000);

在终端运行 node 文件名 即可启动服务器
在浏览器中输入相应地址即可浏览。

app.get方法,用于指定不同访问路径所对应的回调函数,也即路由。

express本质是对node内置模块http的封装。

3、创建中间件

如下创建了两个中间件,

app.use(function(request, response, next) {
  console.log("In comes a " + request.method + " to " + request.url);
  next();
});

app.use(function(request, response) {
  response.writeHead(200, { "Content-Type": "text/plain" });
  response.end("Hello world!\n");
});

在处理每一个http请求时,express会先依次调用(和代码顺序有关)中间件,如果中间件中调用了next则将请求传递给下一个中间件,否则进行请求处理。

可以使用中间件进行路由的过滤等。

同时,可以对指定路径使用中间件,而不是所有的路径。如下:

app.use('/path', someMiddleware);

上面中的someMiddleware中间件,只对path路径的请求有效。

4、请求方法

app.get("/", function(request, response) {
  response.end("Welcome to the homepage!");
});

app.post("/about", function(request, response) {
  response.end("Welcome to the about page!");
});

除了常见的get、post,express还提供了put、delete等一些不常用的方法。

这些方法的第一个参数都是请求地址,除了绝对匹配外,express还支持模糊匹配

5、express的set方法

app.set("views", __dirname + "/views");

app.set("view engine", "jade");

使用set方法为系统变量views和view engine设置值。分别指定视图文件夹的位置和视图渲染的引擎。

6、response的常见方法

方法说明
res.download()Prompt a file to be downloaded.
res.endEnd the response process.
res.json()Send a JSON response.
res.jsonp()Send a JSON response with JSONP support.
res.redirect()Redirect a request.
res.render()Render a view template.
res.send()Send a response of various types.
res.sendFile()Send a file as an octet stream.
res.sendStatus()Set the response status code and send its string representation as the response body.

参见方法说明

7、request的常用属性及方法

见官网说明

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值