[英]Express middleware not sending back body data
我創建了一個快速中間件,在繼續之前檢查用戶令牌作為授權:
import jwt from 'jsonwebtoken';
export const verifyAuthorization = async (req, res, next) => {
try {
const token = req.headers.authorization.split(' ')[1];
if (!token) return res.status(403).send({ error: 'Not authorized' });
const tokenData = jwt.verify(token, 'secret_code');
req.userData = {
userId: tokenData.userId,
fullName: tokenData.fullName,
section: tokenData.section,
groupId: tokenData.groupId,
level: tokenData.level,
};
next();
} catch (error) {
console.log(error);
res.status(403).send({ error: 'Not authorized' });
}
};
我將此中間件應用於路由的所有端點,如下所示:
import { Router } from 'express';
const router = Router();
import item from '../controllers/item_controllers.js';
import { verifyAuthorization } from '../middleware/verifyAuthorization.js';
router.use(verifyAuthorization);
router.post('/all', item.all);
router.post('/new', item.newOne);
router.post('/edit', item.edit);
export default router;
問題是如果授權有問題,它會發回狀態碼而不是正文。 在我的 React 應用程序中,我在控制台上看到 403 錯誤,但它將響應記錄為“未定義”。 controller 函數完美地發回了 json 主體。 我不明白這里的中間件有什么問題。
有任何想法嗎??
謝謝
我修好了它。 我為 http 請求創建的自定義掛鈎存在問題。 它正在錯誤地完成請求而不發回任何數據。 這就是為什么我看到狀態代碼錯誤而不是正文。 我在掛鈎上記錄了響應,它到達了那里。 我剛剛刪除了掛鈎中錯誤塊上的“return”關鍵字,我完美地得到了響應的主體。 謝謝大家的寶貴時間。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.