有人可以帮我确定为什么此 Express 服务器返回 404 吗?

问题描述 投票:0回答:2

此测试因 404 错误而失败,有人可以帮我找出问题所在,因为我真的没有看到问题,我认为我需要第二双眼睛。我正在尝试模拟 Microsoft Graph API 请求以从 Entra 组中删除某人。它在实际代码中运行良好,但我正在尝试使用模拟后端编写集成测试,如您所见。

import axios from "axios";
import express from "express";
import { Server } from "http";

describe.only("fourohfour", () => {
  const app = express();
  app.use(express.json());
  // Entra remove member
  app.delete("graph/groups/:group/members/:userId/$ref", (req, res) => {
    console.log(`ENDPOINT remove ${req.params.group} ${req.params.userId}`);
    res.sendStatus(200);
  });

  let server: Server;

  beforeAll(done => {
    server = app.listen(3001, done);
  });

  afterAll(async () => {
    server.close();
  });

  it("should not four oh four", async () => {
    const res = await axios.delete(
      "http://localhost:3001/graph/groups/123/members/456/$ref",
    );

    expect(res.status).toBe(200);
  });
});
javascript node.js typescript express axios
2个回答
1
投票

正如express文档所述:

如果需要在路径字符串中使用美元字符 ($),请将其转义括在 ([ 和 ]) 内。例如,“/data/$book”处的请求的路径字符串将为“/data/([$])book”。

因此,在您的情况下,将路线架构更改为:

 /graph/groups/:group/members/:userId/([$])ref

应该可以解决问题。


0
投票

我找到原因了,express router中的

$
字符需要像
\\$
一样转义,所以解决方案:

import axios from "axios";
import express from "express";
import { Server } from "http";

describe.only("fourohfour", () => {
  const app = express();
  app.use(express.json());
  // Entra remove member
  app.delete("/graph/groups/:groupId/members/:userId/\\$ref", (req, res) => {
    console.log(`ENDPOINT remove ${req.params.groupId} ${req.params.userId}`);
    res.sendStatus(200);
  });

  let server: Server;

  beforeAll(done => {
    server = app.listen(3001, done);
  });

  afterAll(done => {
    server.close(done);
  });

  it("should not four oh four", async () => {
    const res = await axios.delete(
      "http://localhost:3001/graph/groups/group123/members/user123/$ref",
    );

    expect(res.status).toBe(200);
  });
});
© www.soinside.com 2019 - 2024. All rights reserved.