为了账号安全,请及时绑定邮箱和手机立即绑定

如何在浏览器中模拟请求的错误响应?

如何在浏览器中模拟请求的错误响应?

桃花长相依 2023-12-14 14:22:41
我想在向服务器后端发出 HTTP 请求时使用实际的错误响应来练习我的 JavaScript 错误处理代码。因此,我正在寻找一种简单的方法来模拟响应,使用给定的状态代码、标头、响应正文等。通过msw包,我可以设置一个服务工作人员来捕获请求并生成响应:import { rest } from "msw";const BASE_PATH = "https://localhost:3000";export const handlers = [  rest.get(`${BASE_PATH}/hello`, (req, res, ctx) => {    return res(ctx.status(200), ctx.json({ data: "Hello!" }));  }),  rest.get(`${BASE_PATH}/error`, (req, res, ctx) => {    return res(ctx.status(400), ctx.json({ message: "Bad request" }));  })} 然而,这需要一些代码来连接。如果 Chrome 开发工具中有一些功能可以让我修改响应,就像我可以阻止对某些路由的请求一样,那就更好了。在浏览器中模拟 HTTP 请求响应的最简单方法是什么?
查看完整描述

1 回答

?
梦里花落0921

TA贡献1772条经验 获得超5个赞

好吧,我想似乎没有人有任何值得作为答案的建议,所以我会尝试完全意识到这不会完全回答你的问题。

当我需要一个可以返回各种晦涩的 HTTP 代码以进行测试的 API 时,我会使用此网站: https: //httpstat.us/。这就像附加所需的代码并进行调用(https://httpstat.us/400https://httpstat.us/404https://httpstat.us/200)一样简单

显然,它不能完成您需要的所有“状态代码、标头、响应正文等”,但它肯定会提供测试各种 HTTP 响应代码的能力。


查看完整回答
反对 回复 2023-12-14
?
天涯尽头无女友

TA贡献1831条经验 获得超9个赞

我发现使用页面 URL 查询参数是模拟错误状态的一种非常好的方法:


export const handlers = [

  rest.get(`/your/api/endpoint`, (req, res, ctx) => {


    // Check if the '?error=true' query param has been included in the page url.

    const pageParams = new URLSearchParams(window.location.search);

    const isError = pageParams.get('error') === 'true';


    // Example: http://localhost:3000/your_page_url?error=true

    if (isError) {

      // Query param was found, so return an error response.

      return res(

        ctx.status(404),

        ctx.json({ message: 'Oops! Something went terribly wrong.' })

      );

    }


    // Otherwise - return a 200 OK response.

    return res(ctx.status(200), ctx.json({ data: 'Some cool data' }));

  })

];

查看完整回答
反对 回复 2023-12-14
  • 1 回答
  • 0 关注
  • 62 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信