Nodejs 之 Epress 框架实战
准备
- 安装并新建项目
npm install -g express-generatorexpress -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:8081app.get('/', function (req, res) { console.log("Cookies: ", req.cookies); res.send('Hello , TK !');})
// http://localhost:8081/aboutapp.get('/about', function (req, res) { var data ={name:'TK',age:'26'}; //赋值模版变量 res.render('index', data);})
// http://localhost:8080/contactapp.get('/contact', function (req, res) { res.send('联系我们');})
// http://localhost:8080/detail/1.htmlapp.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)})
关键字:node.js
版权声明
本文来自互联网用户投稿,文章观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处。如若内容有涉嫌抄袭侵权/违法违规/事实不符,请点击 举报 进行投诉反馈!