准备
安装并新建项目
npm install express --save express -e node
新建express.js 文件
var express = require('express'); var app = express(); /* 支持模板文件 */ var path = require('path'); app.set('views', path.join(__dirname, 'views')); app.set('view engine', 'ejs'); /* fs 文件模块 */ var fs = require("fs"); /* cookie-parser cookie模块 */ var cookieParser = require('cookie-parser') /*post表单专用*/ var bodyParser = require('body-parser'); // 创建 application/x-www-form-urlencoded 编码解析 var urlencodedParser = bodyParser.urlencoded({ extended: false }); /*上传专用 * npm install multer --save 安装 **/ var multer = require('multer'); app.use(express.static('public')); app.use(bodyParser.urlencoded({ extended: false })); app.use(multer({ dest: '/tmp/'}).array('image')); /*使用cookie*/ app.use(cookieParser()) /*访问静态文件*/ app.use(express.static('public'));
路由重写
路由重写
// http://localhost:8081 app.get('/', function (req, res) { console.log("Cookies: ", req.cookies); res.send('Hello , TK !'); })
// http://localhost:8081/about app.get('/about', function (req, res) { var data ={name:'TK',age:'26'}; //赋值模版变量 res.render('index', data); })
// http://localhost:8080/contact app.get('/contact', function (req, res) { res.send('联系我们'); })
// http://localhost:8080/detail/1.html app.get('/detail/*.html', function(req, res) { console.log("/*.html GET 请求"); res.send('伪静态'); })
// 调用index.html 文件 app.get('/index.html', function (req, res) { res.sendFile( __dirname + "/" + "index.html" ); })
模版调用
// 用户列表 app.get('/ltpl', function (req, res) { res.render('list', { title: 'List', items: ['A', 'B', 'C', 'D', 'E', 'F'] }); })
调用views/list.ejs
表单/上传处理
post提交
/*post表单处理*/ // 接收post提交 app.post('/post_form_url', urlencodedParser, function (req, res) { // 输出 JSON 格式 response = { salary:req.body.salary, year:req.body.year }; console.log(response); res.end(JSON.stringify(response)); })
get提交
/*get表单处理*/ // 接收get提交 app.get('/get_form_url', function (req, res) { // 输出 JSON 格式 response = { name:req.query.name, age:req.query.age }; console.log(response); res.end(JSON.stringify(response)); })
文件上传
/*上传文件处理*/ app.post('/file_upload', function (req, res) { console.log(req.files[0]); // 上传的文件信息 var des_file = __dirname + "/" + req.files[0].originalname; fs.readFile( req.files[0].path, function (err, data) { fs.writeFile(des_file, data, function (err) { if( err ){ console.log( err ); }else{ response = { message:'File uploaded successfully', filename:req.files[0].originalname }; } console.log( response ); res.end( JSON.stringify( response ) ); }); }); })
RESTful Web Services
json 数据
{ "user1" : { "name" : "tk", "password" : "nopass.8", "profession" : "teacher", "id": 1 }, "user2" : { "name" : "smudge", "password" : "nopass.8", "profession" : "librarian", "id": 2 }, "user3" : { "name" : "julylovin", "password" : "nopass.8", "profession" : "clerk", "id": 3 } }
添加的新用户json数据
var user = { "user4" : { "name" : "mohit", "password" : "password4", "profession" : "teacher", "id": 4 } } app.get('/addUser', function (req, res) { // 读取已存在的数据 fs.readFile( __dirname + "/" + "users.json", 'utf8', function (err, data) { data = JSON.parse( data ); data["user4"] = user["user4"]; console.log( data ); res.end( JSON.stringify(data)); }); })
显示用户详情
app.get('/detail/:id', function (req, res) { fs.readFile( __dirname + "/" + "users.json", 'utf8', function (err, data) { data = JSON.parse( data ); var user = data["user" + req.params.id] console.log( user ); res.end( JSON.stringify(user)); }); })
删除用户
app.get('/delete/:id', function (req, res) { // First read existing users. fs.readFile( __dirname + "/" + "users.json", 'utf8', function (err, data) { data = JSON.parse( data ); delete data["user" + req.params.id]; console.log( data ); res.end( JSON.stringify(data)); }); })
Mysql数据库操作
安装数据库模块
npm install mysql
数据库连接
var mysql = require('mysql'); var connection = mysql.createConnection({ host : 'localhost', user : 'root', password : '', database : 'b2bplus', }); connection.connect();
select 查询
connection.query('SELECT * from cs_user limit 10', function(err, rows, fields) { if (err) throw err; console.log('data: ',JSON.stringify( rows )); });
update 更新
var username = 'Smudge'; connection.query('update cs_user set username = "'+username+'" where user_id = 24', function(err,result) { if (err) throw err; console.log("修改数据成功"); });
insert 插入
var insert_sql = 'insert into cs_user (sid,username) values(1002,"Smudge")'; connection.query(insert_sql, function(err,result) { if (err) throw err; console.log("插入数据成功"); });
delete 删除
connection.query('delete from cs_user where username= "Smudge"', function(err,result){ if (err) throw err; console.log("删除数据成功"); });
监听端口
var server = app.listen(8080, function () { var host = server.address().address var port = server.address().port console.log("应用实例,访问地址为 http://%s:%s", host, port) })
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。