Nodejs 入门3 Express试用

来源:互联网 发布:江宁网络问政 修文路 编辑:程序博客网 时间:2024/05/16 18:39

Express


中文网址:http://www.expressjs.com.cn/

安装

mkdir myappcd myappnpm initnpm install express --save  --save意思是加入依赖表

新建程序 app.js

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);});

监听 : 3000 端口
路由:所有 (/) URL 或 路由 返回 “Hello World!” 字符串,其他所有路径全部返回 404 Not Found。

req (请求) 和 res (响应) 与 Node 提供的对象完全一致,因此,你可以调用 req.pipe()、req.on(‘data’, callback) 以及任何 Node 提供的方法。

启动server

node app.js

在浏览器访问:http://localhost:3000
显示Hello World
这里写图片描述

express应用生成器

npm install express-generator -gexpress myappcd myappnpm installset DEBUG=myapp & npm start

访问http://127.0.0.1:3000/

这里写图片描述

express 简单路由

// 对网站首页的访问返回 "Hello World!" 字样app.get('/', function (req, res) {  res.send('Hello World!');});// 网站首页接受 POST 请求app.post('/', function (req, res) {  res.send('Got a POST request');});///user 节点接受 PUT 请求app.put('/user', function (req, res) {  res.send('Got a PUT request at /user');});///user 节点接受 DELETE 请求app.delete('/user', function (req, res) {  res.send('Got a DELETE request at /user');});///secret 节点接受所有请求app.all('/secret', function (req, res, next) {  console.log('Accessing the secret section ...');  next(); // pass control to the next handler});
0 0
原创粉丝点击