页面可以正常访问,但是其中的静态资源是404 GEThttp://localhost:3000/public/bundle.js404 (Not Found) 目录结构如下: app server.js public bundle.js 以下是server.js 'use strict'constkoa =require('koa')constrender =require('koa-ejs')constpath =require('path')constlogger =require('koa-logger')co...
// 错误处理,如果是文件不存在,返回404,否则返回500 const notfound = ['ENOENT', 'ENAMETOOLONG', 'ENOTDIR'] if (notfound.includes(err.code)) { // createError来自http-errors库,可以快速创建HTTP错误对象 // github地址:https://github.com/jshttp/http-errors throw createError(404, err) } err....
// 错误处理,如果是文件不存在,返回404,否则返回500 const notfound = ['ENOENT', 'ENAMETOOLONG', 'ENOTDIR'] if (notfound.includes(err.code)) { // createError来自http-errors库,可以快速创建HTTP错误对象 // github地址:https://github.com/jshttp/http-errors throw createError(404, err) } err....
} }catch(err) {// 错误处理,如果是文件不存在,返回404,否则返回500constnotfound = ['ENOENT','ENAMETOOLONG','ENOTDIR']if(notfound.includes(err.code)) {// createError来自http-errors库,可以快速创建HTTP错误对象// github地址:https://github.com/jshttp/http-errorsthrowcreateError(404, err) } e...
const notfound= ['ENOENT', 'ENAMETOOLONG', 'ENOTDIR']if(notfound.includes(err.code)) {throwcreateError(404, err) } err.status= 500throwerr } 一个小彩蛋 可以发现一个很有意思的事情,如果发现当前路径是一个目录以后,并且明确指定了format,那么还会再尝试拼接一次index。
本文会接着讲一个常用的中间件---koa-static,这个中间件是用来搭建静态服务器的。 其实在我之前使用Node.js原生API写一个web服务器已经讲过怎么返回一个静态文件了,代码虽然比较丑,基本流程还是差不多的: 通过请求路径取出正确的文件地址 通过地址获取对应的文件 使用...
notFoundFile {string} optional default file to serve if requested static is missing log {boolean} request access log to console last {boolean} don't execute any downstream middleware. (defaults to true) maxage Browser cache max-age in milliseconds. (defaults to 0) hidden Allow transfer of hi...
:string|undefined;/*** optional default file to serve if requested static is missing*/notFoundFile?:string|undefined;/*** request access log to console*/log?:boolean|undefined;/*** don't execute any downstream middleware. defaults to true*/last?:boolean|undefined;/*** Browser cache max-...
: HTTP Request KoaServer->>StaticCache: Process Static File Request StaticCache->>FileSystem: Check File Existence alt File Exists FileSystem-->>StaticCache: Return File Metadata StaticCache->>Client: Serve File with Caching Headers else File Not Found StaticCache->>Client: 404 Not Found end...
extensionsTry to match extensions from passed array to search for file when no extension is sufficed in URL. First found is served. (defaults tofalse) Example constserve=require("koa-static");constKoa=require("koa");constapp=newKoa();// $ GET /package.jsonapp.use(serve("."));// $...