对于尚未定义的路由,Express 服务器返回 200

Pav*_*ndu 2 node.js express axios

几天来我一直面临着一件奇怪的事情,到目前为止我还没有解决这个问题。问题是我有一个 React.js 前端、Node Express.js 后端和 MongoDB,当我使用/api/users/update-pwd正确的参数发出请求时axios,它不会更新密码,但返回 200。然后,我尝试了一些路线例如/api/users/psosp。令我惊讶的是,它也返回了 200。我找不到原因。任何有用的提示都将受到高度赞赏。

Axios.post("/users/update-password",{
       password: n_pwd
}).then(
     res => {
        alert("Password Updated")
     }
).catch(err => {
     console.log(err)
     alert("An error occured")
})
Run Code Online (Sandbox Code Playgroud)

Nik*_*uri 5

确保您的后端没有这样的代码。

router.post('/users/:userId',(req,res)=>{
// some operations
res.send();
});

router.post('users/update-password',(req,res)=>{
// some operations
res.send();
});

Run Code Online (Sandbox Code Playgroud)

上面的作用是,无论你使用什么来代替*, /users/*/ 默认情况下都会调用第一个路由

并确保您没有使用

app.use('*',(req,res)=>{
// some operations
res.send();
})
Run Code Online (Sandbox Code Playgroud)

对于任何 API 调用,无论路径如何,都将调用上述代码。