标签:des style blog http color io os java ar
因为Express.js的不同版本的api有差异,本文的代码针对express 3.2.5
----package.json
----index.js
1.在项目目录下建立文件,package.json,这个文件是npm安装项目所需包的依据。
package.json
{ "name": "hello-world", "description": "hello world test app", "version": "0.0.1", "private": true, "dependencies": { "express": "3.2.5" } }
2.在命令行窗口打开项目所以在目录通过npm安装项目依赖包,安装后出现文件夹node_modules,其中包含了express包:
npm install
3.建立文件index.js.Express提供了"routing"这个东西,其实就是,app.get(),app.post(),app.all(),这个三个函数,第一参数是路径,第一个参数是一个回调函数。
index.js
var express = require("express"); var http = require("http"); var app = express(); app.all("*", function(request, response, next) { response.writeHead(404, { "Content-Type": "text/plain" }); next(); }); app.get("/", function(request, response) { response.end("Welcome to the homepage!"); }); app.get("/about", function(request, response) { response.end("Welcome to the about page!"); }); app.get("*", function(request, response) { response.end("404!"); }); http.createServer(app).listen(3000);
4.浏览器端访问URL:
http://127.0.0.1:3000
浏览器端访问URL:
http://127.0.0.1:3000/about
浏览器端访问URL:
http://127.0.0.1:3000/*
标签:des style blog http color io os java ar
原文地址:http://www.cnblogs.com/IanI/p/3994543.html