【问题标题】:Node Express JEST Supertest PUT and DELETE endpoints return 405 "Method Not Allowed"Node Express JEST Supertest PUT 和 DELETE 端点返回 405“方法不允许”
【发布时间】:2022-03-25 13:38:53
【问题描述】:

我正在使用 Express 和 suppertest 在 Node 上运行一个简单的测试。有 10 个测试,其中 POST 和 GET 测试运行良好(前 6 个测试)。其他四个具有 PUT 和 DELETE 的返回 405“方法不允许”。这是我的代码:

test('Should login existing user', async () => {
  await request(app)
        .post('/api/auth')
        .send({ 
          email: userOne.email,
          password: userOne.password
        })
        .expect(200);
});


test('Should NOT login nonexisting user', async () => {
  await request(app)
        .post('/api/auth')
        .send({ 
          email: userThree.email,
          password: userThree.password
        })
        .expect(400);
});


test('Should get profile for authenticated user', async () => {
  await request(app)
        .get('/api/auth')
        .set('x-auth-token', userOne.token)
        .expect(200)
});


test('Should NOT get profile for unauthenticated user', async () => {
  await request(app)
        .get('/api/auth')
        .expect(401)
});


test('Should create a new user', async () => {
  await request(app)
        .post('/api/person')
        .set('x-auth-token', userOne.token)
        .send({ ...userTwo })
        .expect(201);
});


test('Should NOT create a new user', async () => {
  await request(app)
        .post('/api/person')
        .send({ ...userTwo })
        .expect(401);
});


test('Should update user for autheticated user', async () => {
  await request(app)
        .put('api/person/2')
        .set('x-auth-token', userOne.token)
        .send({ role: 1})
        .expect(200)
});


test('Should NOT update user for unauthenticated user', async () => {
  await request(app)
        .put('api/person/2')
        .send({ role: 1})
        .expect(401)
});


test('Should delete user for autheticated user', async () => {
  await request(app)
        .delete('api/person/2')
        .set('x-auth-token', userOne.token)
        .send()
        .expect(200)
});


test('Should NOT delete user for unauthenticated user', async () => {
  await request(app)
        .delete('api/person/2')
        .expect(401)
});

正如我上面所说,无论有无身份验证,前六名都非常出色。带有 PUT 和 DELETE 请求的底部 4 个返回 405“方法不允许”。用邮递员测试相同的路线我没有遇到任何问题。 DELETE 和 POST 方法都按预期工作。有谁知道我做错了什么?我在看什么?感谢您的所有帮助。

【问题讨论】:

    标签: node.js express jestjs supertest


    【解决方案1】:

    DELETE 和 PUT 方法没有任何问题。原因是一个简单的错字(在 'api/person/2' 调用前面缺少 /)。不幸的是,这只发生在 DELETE 和 PUT 方法中,这使得调试需要更长的时间,认为问题出在方法上。这个错误要简单得多。路径不正确。

    【讨论】:

      猜你喜欢
      • 2019-10-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-23
      • 2019-03-05
      • 1970-01-01
      • 2013-04-01
      • 2020-12-15
      相关资源
      最近更新 更多