开发者问题收集

[未接收应用错误]:TypeError-无法读取未定义的属性(读取'名称')

2021-10-11
3611

当我尝试使用 Postman 测试 /api/register 端点并执行以下 POST 请求时,收到此错误消息:

{
    "name" : "first",
    "email" : "[email protected]",
    "password" : "123"
}
[uncaught application error]: TypeError - Cannot read properties of undefined (reading 'name')

    request: { url: "http://0.0.0.0:8000/api/register", method: "POST", hasBody: true }
    response: { status: 404, type: undefined, hasBody: false, writable: true }
    
        at register (file:///C:/Users/m/app_back/controllers/auth_controller.ts:9:22)
        at async dispatch (https://deno.land/x/[email protected]/middleware.ts:41:7)
        at async dispatch (https://deno.land/x/[email protected]/middleware.ts:41:7)
        at async dispatch (https://deno.land/x/[email protected]/middleware.ts:41:7)
        at async EventTarget.#handleRequest (https://deno.land/x/[email protected]/application.ts:379:9)
    TypeError: Cannot read properties of undefined (reading 'name')
        at register (file:///C:/Users/m/app_back/controllers/auth_controller.ts:9:22)
        at async dispatch (https://deno.land/x/[email protected]/middleware.ts:41:7)
        at async dispatch (https://deno.land/x/[email protected]/middleware.ts:41:7)
        at async dispatch (https://deno.land/x/[email protected]/middleware.ts:41:7)
        at async EventTarget.#handleRequest (https://deno.land/x/[email protected]/application.ts:379:9)

这是我的 auth_controller.ts 文件:

import {
      create, verify, decode, getNumericDate, RouterContext, hashSync, compareSync
    } from "../deps.ts";
    import { userCollection } from "../mongo.ts";
    import User from "../models/user.ts";
    
    export class AuthController {
      async register(ctx: RouterContext) {
        const { value: { name, email, password } } = await ctx.request.body().value;
    
        let user = await User.findOne({ email });
        if (user) {
          ctx.response.status = 422;
          ctx.response.body = { message: "Email is already used" };
          return;
        }
        const hashedPassword = hashSync(password);
        user = new User({ name, email, password: hashedPassword });
        await user.save();
        ctx.response.status = 201;
        ctx.response.body = {
          id: user.id,
          name: user.name,
          email: user.email
        };
      }
      async login(ctx: RouterContext) {
        const { value: { email, password } } = await ctx.request.body().value;
        if (!email || !password) {
          ctx.response.status = 422;
          ctx.response.body = { message: "Please provide email and password" };
          return;
        }
        let user = await User.findOne({ email });
        if (!user) {
          ctx.response.status = 422;
          ctx.response.body = { message: "Incorrect email" };
          return;
        }
        if (!compareSync(password, user.password)) {
          ctx.response.status = 422;
          ctx.response.body = { message: "Incorrect password" };
          return;
        }
    
        const key = await crypto.subtle.generateKey(
          { name: "HMAC", hash: "SHA-512" },
          true,
          ["sign", "verify"],
        );
    
        const jwt = create( { 
          alg: "HS256",
          typ: "JWT",
        }, {
          iss: user.email,
          exp: getNumericDate(
            Date.now() + parseInt(Deno.env.get("JWT_EXP_DURATION") || "0"))
        },
        key
        );
    
        ctx.response.body = {
          id: user.id,
          name: user.name,
          email: user.email,
          jwt,
        };
      }
    }
    
    export default new AuthController();

这是什么问题,我该如何解决?

编辑:我在代码中添加了以下行:

console.log( await ctx.request.body().value );

结果如下:

{ name: "first", email: "[email protected]", password: "123" }
1个回答

您遇到此问题是因为您正尝试访问 ctx.request.body().value.value.name (请注意多个 value 属性)。您可以将 auth_controller.ts 的第 9 行更改为此以修复它:

const { name, email, password } = await ctx.request.body().value;

另外,我还注意到您当前的代码中存在一些其他问题。

您的 JWT 算法和生成的密钥加密算法应该匹配

因此,请将 第 47 行 上的哈希加密更改为 SHA-256 ,或将 第 53 行 上的 JWT 算法更改为 HS512

您不需要将当前日期传递给 getNumericDate 函数

此辅助函数已经为您完成了这项工作,您需要在此处传递的只是您希望令牌过期的时间段(以秒为单位)。在您的情况下,它将是:

getNumericDate(Deno.env.get("JWT_EXP_DURATION") || 0)}
Renat Zaicev
2021-10-31