node初体验(二)
1.静态资源访问,需要设置路由和响应标头
2.url模块、path模块、querystring模块
Url {
protocol: null,
slashes: null,
auth: null,
host: null,
port: null,
hostname: null,
hash: null,
search: '?id=10021',
query: 'id=10021',
pathname: '/a.html',
path: '/a.html?id=10021',
href: '/a.html?id=10021'
}
- url.parse(,true).query 可以以对象形式输出查询参数
- path.parse 可以获得拓展名
- querystring 将查询参数字符串转成对象形式
MIME
是设定某种扩展名的文件用一种应用程序来打开的方式类型,当该扩展名文件被访问的时候,浏览器会自动使用指定应用程序来打开
{
".html": "text/html" ,
".png": "image/png",
".jpeg": "image/jpeg" ,
".jpg": "image/jpeg",
".json": "application/json",
".ico": "image/x-icon" ,
".svg": "image/svg+xml",
".mp4": "video/mp4" ,
".mp3":"audio/mpeg",
".avi": "video/x-msvideo",
".docx": "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
".doc": "application/msword",
".xls": "application/vnd.ms-excel" ,
".xlsx": "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" ,
".css": "text/css" ,
".js": "application/x-javascript"
}
3.根据拓展名匹配对应类型的标头
var pathname=url.parse(req.url).pathname
var extname=path.extname(pathname)
if(mine_json.hasOwnProperty(extname))
{
res.setHeader("content-type",mime[extname])
}
- 重定向
res.writeHead(302,{"Location":pathname+"/index.html"})
4.serve-static资源静态化
npm install serve-static
npm install finalhandler
var finalhandler = require('finalhandler')
var http = require('http')
var serveStatic = require('serve-static')
var serve = serveStatic('public', { 'index': ['index.html', 'index.htm'] })
var server = http.createServer(function onRequest(req, res) {
serve(req, res, finalhandler(req, res))
})
server.listen(3000)
5.formidable实现对get和set的封装或者文件上传等
6.app.use和请求方式无关
app.use("/use/:id".function(req,res,next){
console.log("中间件");
res.send("OK")
})
app.get("/use/:id".function(req,res,next){
console.log("中间件");
res.send("OK")
})
7.应用层中间件感觉和路由中间件差不多,路由中间件最后还要绑定到应用层中间件,但是当路由多了以后,再把路由写在一个app里面就不合适了,使用用路由中间件拓展性更好。
8.错误处理中间件
app.use(function (err, req, res, next) {
console.error(err.stack)
res.status(500).send('Something broke!')
})
9.rjs模板引擎的使用
var express = require("express")
var fs = require("fs")
var path = require("path")
var app = express()
//设置默认的模板引擎
app.set("view engine", "ejs")
app.get("/", function (req, res, next) {
res.render("deptinfo", {
"deptname": "IT",
"deptno": "001",
"emps": [
{ "name": "TOM", "age": 30 },
{ "name": "JACK", "age": 35 },
{ "name": "ROSE", "age": 20 },
]
})
})
//静态资源处理
// app.use('/static', express.static('public'))
app.use('/static', express.static(path.join(__dirname, 'public')))
app.use(express.static('uploads'))
app.listen(3000, () => {
console.log("服务已启动。port:3000")
})

浙公网安备 33010602011771号