本文共 3668 字,大约阅读时间需要 12 分钟。
??????????????????????JavaScript ?????????????????????????????????
function static(root, options = {}) { const { dotfiles = "ignore", etag = true, lastModified = true, maxAge = 0, setHeaders } = options; return function (req, res, next) { const { pathname } = url.parse(req.url, true); const file = path.join(root, pathname); const parts = file.split(path.sep); const isDotFile = parts[parts.length - 1][0] === "."; if (isDotFile && dotfiles === "deny") { res.setHeader("Content-Type", "text/html"); res.statusCode = 403; return res.end(http.STATUS_CODES[403]); } fs.stat(file, (error, stat) => { if (error) { next(); } else { if (etag) { res.setHeader("ETag", stat.mtime.toLocaleDateString()); } if (lastModified) { res.setHeader("Last-Modified", stat.mtime.toUTCString()); } if (typeof setHeaders === "function") { setHeaders(req, req, (params) => { console.log(params); }); } res.setHeader("Cache-Control", `max-age=${maxAge}`); res.setHeader("Content-Type", mime.getType(file)); fs.createReadStream(file).pipe(res); } }); };} bodyParser ?????????????????????????????????????
function json(options) { return function (req, res, next) { const contentType = req.headers["content-type"]; if (contentType === "application/json") { const buffer = []; req.on("data", (data) => { buffer.push(data); }); req.on("end", () => { const result = buffer.toString(); req.body = JSON.parse(result); next(); }); } else { next(); } };} function urlencoded(options) { const { extended } = options; return function (req, res, next) { const contentType = req.headers["content-type"]; if (contentType === "application/x-www-form-urlencoded") { const buffer = []; req.on("data", (data) => { buffer.push(data); }); req.on("end", () => { const result = buffer.toString(); if (extended) { req.body = qs.parse(result); } else { req.body = querystring.parse(result); } next(); }); } else { next(); } };} function text(options) { return function (req, res, next) { const contentType = type.parse(req.headers["content-type"]); const charset = contentType.parameters.charset; const cType = contentType.type; if (cType === "text/plain") { const buffer = []; req.on("data", (data) => { buffer.push(data); }); req.on("end", () => { const r = Buffer.concat(buffer); if (charset === "gbk") { req.body = iconv.decode(r, charset); } else { req.body = buffer.toString(); } next(); }); } else { next(); } };} ???????? Express ????????????????????????????
转载地址:http://tld.baihongyu.com/