const Koa = require("koa"); const multer = require("@koa/multer"); const bodyParser = require("koa-bodyparser"); const Router = require("@koa/router"); const jwt = require("jsonwebtoken"); const crypto = require("crypto"); const app = new Koa(); const router = new Router({ prefix: "/api" }); const secretKey = crypto.randomBytes(32).toString("hex"); const storage = multer.diskStorage({ destination: function (req, file, cb) { cb(null, "./uploads"); }, filename: function (req, file, cb) { cb(null, "123" + file.fieldname + "-" + Date.now() + file.originalname); // cb(null, file.originalname); }, }); const upload = multer({ storage }); const authMiddleware = (ctx, next) => { const token = ctx.headers.authorization; if (!token) { ctx.status = 401; return (ctx.body = { code: -1001, message: "未提供令牌" }); } next(); }; router.use(bodyParser()); router.post("/login", (ctx) => { const { name, password } = ctx.request.body; if (name === "lingo123" && password === "123456") { const token = jwt.sign({ name }, secretKey); ctx.body = { code: 0, data: { id: 1, name, token, }, }; } }); router.use(authMiddleware); router.get("/users/:id", (ctx) => { const id = ctx.request.params.id; ctx.body = id; }); router.post("/upload", upload.single("photo"), (ctx) => { console.log("upload"); ctx.body = "upload"; }); app.use(router.routes()); app.listen(3000, () => { console.log("服务器启动成功~"); }); 初学 nodejs,想请教大佬,我想在文件上传这个接口模拟一个 token 校验功能,但是出现了问题,通过 postman 发送上传请求, koa 这边没有问题, postman 接收到的是 404 Not Found,而在将 authMiddleware 修改为异步后就没有问题了?这是为什么?其他的比如 /users/:id 都是可以正常响应的.
