對于一個前端開發人員來說,node.js可以說是開發后端的福音。本人畢設項目使用的是asp.net(只是使用ashx來接收前端的ajax,并沒有使用那些惡心的控件),通過對比發現整個項目都使用js實在是幸福。
###Node.js
關于node.js的優點就不再多說,網上一搜一大堆,項目也可以找到很多。這里主要說一下node.js關于搭建web應用這一塊的缺點。
眾所周知,node.js需要自己搭建服務器,也就是說你需要自己監聽一個端口并啟動它
~~~
var http=require('http');
http.createServer(function(req,res) {
res.writeHead(200, {'Content-Type': 'text/plain'});
res.write("hello sunnychuan");
res.end();
}).listen(3000);
console.log("server is running!");
~~~
這里有一本電子書幫助你使用原生的node.js搭建web應用,[點擊這里](http://www.nodebeginner.org/index-zh-cn.html#a-basic-http-server)
不僅僅是監聽端口,我們往往會根據用戶輸入的url從本地找到相應文件并將它寫回請求
~~~
fs.exists(filePath,function(exists){
if(exists){
res.writeHead(200,{'Content-Type':contentType});
var stream=fs.createReadStream(filePath);
stream.on('error',function(){
res.writeHead(500,{'Content-Type':'text/html'});
res.end('<h1>500 Server Error</h1>');
});
stream.pipe(res);
}
}
~~~
我們還會針對前端的ajax請求做路由處理
~~~
//根據不同的路徑調用不同的處理程序
var handle={};
handle["/api/get.json"]=requestHandlers.get;
handle["/api/post.json"]=requestHandlers.post;
~~~
~~~
function route(handle,pathname,req,res){
if(typeof handle[pathname]==='function'){
handle[pathname](req,res);
}
else{
res.writeHead(404,{'Content-Type':'text/html'});
res.write('<h1>404 Not Found</h1>');
res.end();
}
}
~~~
~~~
var pathname=decodeURI(url.parse(req.url).pathname);
if(path.extname(pathname)=='.json'){
route(handle,pathname,req,res);
}
~~~
通過上面那么一折騰,原本的熱情就消退了一半,這里我推薦一下express框架,官方文檔在[這里](http://www.expressjs.com.cn/)
###Express
####安裝和目錄結構
首先安裝express
~~~
npm install express --save-dev
~~~
安裝express的應用生成器
~~~
npm install express-generator -g
~~~
使用它的應用生成器可以很快建立一個項目
~~~
express myapp
~~~
然后進入到該文件夾下,安裝所有依賴
~~~
cd myapp
npm install
~~~
你的目錄結構長這個樣子

bin是啟動項,在bin/www里面你可以修改端口號
node_modules用來存放npm安裝的模塊
public里面用來存放資源
routes是路由控制,存放了所有的處理程序
views是視圖文件,相當于html頁,在routes中會使用類似
~~~
router.get('/', function(req, res, next) {
res.render('index', { title: 'Express' });
});
~~~
這樣的代碼來替換模板引擎里的內容,有點像java的.jsp文件和asp.net的.asp文件
app.js用來配置express,你可以在這里進行路由分配和錯誤處理并按需加載中間件
####啟動項目
~~~
npm start
~~~

####修改代碼
作為前端開發的你,也許會厭惡由后端直接將數據渲染在頁面上(至少我是這樣),我們通常使用ajax來進行前后端交互并自行處理后端的數據,因此整個views文件就可以直接delete掉了。
step1 更改目錄結構
把public更名為client,新建server文件夾并把routes和app.js放到里面(views直接刪除即可),這樣一來整個項目結構就比較明顯了,客戶端和服務端分離。

step2 修改routes文件夾
routes里默認有index.js和users.js兩個路由文件,其中index.js是負責模板渲染的
~~~
var express = require('express');
var router = express.Router();
/* GET home page. */
router.get('/', function(req, res, next) {
res.render('index', { title: 'Express' });
});
module.exports = router;
~~~
而users.js是直接返回一個字符串
~~~
var express = require('express');
var router = express.Router();
/* GET users listing. */
router.get('/', function(req, res, next) {
res.send('respond with a resource');
});
module.exports = router;
~~~
既然我們刪掉了views,那么index.js的代碼肯定要修改的。我刪掉了這兩個文件,并新建了get.js和post.js文件用來接收和處理前端的ajax請求
~~~
//get.js
module.exports=function(req,res){
console.log(req.query.userName);
res.json({code:200,data:"this is a get request"});
}
~~~
~~~
//post.js
module.exports=function(req,res){
console.log(req.body.userName);
console.log(req.body.password);
res.json({code:200,data:"this is a post request"});
}
~~~
另外,我還新建了一個名為router.js的文件,用來分配路由(默認是在app.js文件中進行路由分配的,但是一旦請求過多,app.js會十分冗長)
~~~
var express=require('express');
var router=express.Router();
var get=require('./get');
var post=require('./post');
router.get('/get.json',get);
router.post('/post.json',post);
module.exports=router;
~~~
step3 修改app.js
對模塊加載做如下修改
~~~
//修改前
var index = require('./routes/index');
var users = require('./routes/users');
//修改后
var router=require('./routes/router.js');
~~~
刪掉視圖引擎的設置
~~~
//刪除下面的代碼
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
~~~
對靜態資源的加載做一些更改,默認是在"public"文件夾下讀取并加載靜態資源的,現在我們設置為先從根路徑讀取文件,如果不存在則從"client"中讀取文件
~~~
//修改前
app.use(express.static(path.join(__dirname, 'public')));
//修改后
var rootDir=path.resolve(__dirname);
var projectDir=path.resolve(__dirname,'../','client');
app.use(express.static(rootDir));
app.use(express.static(projectDir));
~~~
替換默認的路由加載,改為上面require的router。/api是一個虛擬路徑,這樣每當我們訪問/api/xxx.json就會通過路由來分配不同的控制器完成業務邏輯
~~~
//修改前
app.use('/', index);
app.use('/users', users);
//修改后
app.use('/api',router);
~~~
我們還需要讓根路徑加載首頁面
~~~
app.get('/', function(req, res){
res.sendFile(projectDir+'/index.html');
});
~~~
由于不需要渲染視圖,因此錯誤頁面的處理也要進行修改,我這里僅僅是把錯誤信息返回給前端
~~~
//修改前
app.use(function(err, req, res, next) {
res.locals.message = err.message;
res.locals.error = req.app.get('env') === 'development' ? err : {};
res.status(err.status || 500);
res.render('error');
});
//修改后
app.use(function(err, req, res, next) {
res.locals.message = err.message;
res.locals.error = req.app.get('env') === 'development' ? err : {};
res.status(err.status || 500);
res.json({code:500,msg:"error"});
});
~~~
####測試
我們需要編寫前端代碼進行測試,這里我使用angular簡單地發送get和post請求
~~~
angular.module("indexApp",[])
.controller("IndexCtrl",function($scope,$http){
$scope.get=function(){
$http({
method:"get",
url:"/api/get.json",
params:{userName:"sunnychuan"}
}).then(function(res){
if(res.data.code==200){
console.log(res.data.data);
}
else if(res.data.code==500){
console.log(res.data.msg);
}
})
}
$scope.post=function(){
$http({
method:"post",
url:"/api/post.json",
data:{userName:"sunnychuan",password:"qc"}
}).then(function(res){
if(res.data.code==200){
console.log(res.data.data);
}
else if(res.data.code==500){
console.log(res.data.msg);
}
})
}
})
~~~
同樣的,使用npm start啟動項目,在url中輸入localhost:3000

點擊get按鈕


點擊post按鈕


至此,基本的環境搭建成功,搭配mongodb會在之后的文章中介紹。
- html/css
- 不一樣的css3之Transform
- 不一樣的css3之Transition
- 不一樣的css3之Animation
- Less初學
- Sass初學
- 水平垂直居中那些事
- css優先級
- css基礎教學
- javascript
- 淺談javascript事件處理程序
- cookie,localStorage,sessionStorage的區別
- Ajax
- 說說JSON
- 數組常用的方法
- 字符串常用的方法
- 閉包之我的理解
- 常用DOM操作
- 扒一扒所謂的面向對象
- JS Blob對象
- ES6學習筆記(一)
- ES6學習筆記(二)
- 用ES6書寫React
- React+Redux實戰總結
- 基于Express搭建開發環境
- 其他
- github初學
- 輕松配置Webpack
- asp.net學習筆記
- ado.net
- 如何使用ajax進行前后端交互
- 銀行大廳自助服務系統需求分析
- 西電銀行開發手冊
- 接口
- ajax