var express = require('express'); var app = express(); var fs = require("fs"); var bodyParser = require('body-parser'); var multer = require('multer'); app.use('/public', express.static('public')); app.use(bodyParser.urlencoded({ extended: false })); app.use(multer({ dest: '/tmp/'}).array('image')); app.get('/index.html', function (req, res) { res.sendFile( __dirname + "/" + "index.html" ); }) 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.writeHead(200,{'Content-Type':'text/html;charset=utf-8'}); res.end( JSON.stringify( response ) ); }); }); }) var server = app.listen(8081, '0.0.0.0', function () { var host = server.address().address var port = server.address().port console.log("瀏覽地址為 http://%s:%s", host, port) })
執行結果如下:
1 2
$ node server.js 瀏覽地址為 http://0.0.0.0:8081
開啟瀏覽器瀏覽:
1
http://0.0.0.0:8080/index.html
Cookie 管理
安裝 cookie-parser
1
npm install cookie-parser --save
express_cookie.js
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
var express = require('express') var cookieParser = require('cookie-parser') var util = require('util'); var app = express() app.use(cookieParser()) app.get('/', function(req, res) { console.log("Cookies: " + util.inspect(req.cookies)); }) var server = app.listen(8081, '0.0.0.0', function () { var host = server.address().address var port = server.address().port console.log("瀏覽地址為 http://%s:%s", host, port) })