您的位置:首页 > Web前端 > Node.js

node 小结

2015-07-13 15:33 771 查看
express

node可以直接使用http module来实现web应用。

var http = require("http");

// 创建Server
var app = http.createServer(function(request, response) {
response.writeHead(200, {
"Content-Type": "text/plain"
});
response.end("Hello hyddd!\n");
});

// 启动Server
app.listen(1984, "localhost");


访问http://localhost:1984 即可

同时 web应用需要访问不同的url http也可以实现:

// 加载所需模块
var http = require("http");

// 创建Server
var app = http.createServer(function(request, response) {
if(request.url == '/'){
response.writeHead(200, { "Content-Type": "text/plain" });
response.end("Home Page!\n");
} else if(request.url == '/about'){
response.writeHead(200, { "Content-Type": "text/plain" });
response.end("About Page!\n");
} else{
response.writeHead(404, { "Content-Type": "text/plain" });
response.end("404 Not Found!\n");
}
});

// 启动Server
app.listen(1984, "localhost");


中间件: middleware

// 加载所需模块
var express = require("express");
var http = require("http");

// 创建server
var app = express();

// 增加一些middleware
app.use(function(request, response, next) {
console.log("step1, url:" + request.url);
next();
});
app.use(function(request, response, next) {
console.log("step2");
if(request.url == '/'){
response.writeHead(200, { "Content-Type": "text/plain" });
response.end("Main Page!\n");
}
next();
});
app.use(function(request, response, next) {  console.log("step2:");
console.log("step3");
if(request.url == '/about'){
response.writeHead(200, { "Content-Type": "text/plain" });
response.end("About Page!\n");
}
});

// 启动server
http.createServer(app).listen(1984);


Express通过 app.use 注册middleware,middlewares相当于request的handlers,在处理request时,顺序执行每一个handler(function),handler业务完成后,通过调用next();,决定是否调用下一个handler。

路由: routing

var express = require("express");
var http = require("http");
var app = express();

app.all("*", function(request, response, next) {
console.log("step1");
next();
});

app.get("/", function(request, response) {
response.end("Home Page!");
});

app.get("/about", function(request, response) {
response.end("About Page!");
});

app.get("*", function(request, response) {
response.end("404!");
});

http.createServer(app).listen(1984);


使用express实现路由。

同时 express支持模板的view处理

var express = require("express");
var app = express();

// 模板目录:./views
app.set("views", __dirname + "/views");

// 使用jade引擎
app.set("view engine", "jade");

// 寻址views/index,提交jade渲染,并返回结果
app.get("/", function(request, response) { response.render("index", { message: "I'm hyddd" }); });


使用jade引擎来渲染模板。

node中重要概念: 流

流的对接:
require('fs').createReadStream('image.jpg').pipe(res)


net(telnet)服务器返回的是连接对象 http返回的是request和response对象
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  node require