首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何从msw模拟请求体中检索数据

如何从msw模拟请求体中检索数据
EN

Stack Overflow用户
提问于 2022-09-26 22:27:40
回答 1查看 368关注 0票数 0

我试图使用msw检索模拟api调用中的数据,同时使用类型记录。我该怎么做呢?我不断收到“属性‘电子邮件’在‘DefaultBodyType’类型中不存在”

处理程序

代码语言:javascript
复制
export const handlers: RestHandler[] = [
  rest.post(`/${API_VERSION}/authentication/login`, (req, res, ctx) => {
    const {email} = req.body;
    console.log();
    return res(
      ctx.status(200),
      ctx.json({
        token: "abdb23231232jdsaWEDwdxaCDA",
        expiresIn: 100000,
        isEnabled: true,
        isLocked: false,
      })
    );
  })
];
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2022-10-06 09:56:01

您需要为处理程序本身提供一些类型,描述请求主体和响应主体应该是什么样子。

代码语言:javascript
复制
interface LoginRequestBody {
  email: string;
}

interface LoginResponseBody {
  token: string,
  expiresIn: number;
  isEnabled: boolean;
  isLocked: boolean,
}

export const handlers = [
  rest.post<LoginRequestBody, LoginResponseBody>(`/${API_VERSION}/authentication/login`, (req, res, ctx) => {
    const {email} = req.body;
    console.log();
    return res(
      ctx.status(200),
      ctx.json({
        token: "abdb23231232jdsaWEDwdxaCDA",
        expiresIn: 100000,
        isEnabled: true,
        isLocked: false,
      })
    );
  })
];

您也不需要RestHandler[],因为它是推断的。

MSW维护者编写的这篇文章也有助于更多地了解类型。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/73860561

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档