在节点表达的DELETE端点中找不到参数

时间:2019-01-18 23:57:41

标签: javascript node.js express

我无法在删除端点中访问提供的url参数,我也不知道为什么。 GET,POST和PUT正常工作。

const express  = require("express");
const app = express();
app.use(express.json());

const courses = [
    {id: 1, name: 'course1'},
    {id: 2, name: 'course2'},
    {id: 3, name: 'course3'},
];

app.delete('/api/courses/:id', (res, req) => {
    console.log(req.params.id);
});

我在邮递员中进行了删除操作,提供了网址“ localhost:5000 / api / courses / 1”,并且得到了响应:

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="utf-8">
        <title>Error</title>
    </head>
    <body>
        <pre>TypeError: Cannot read property &#39;id&#39; of undefined
            <br> &nbsp; &nbsp;at app.delete (C:\Users\Ove\WebstormProjects\Vidley\index.js:84:28)
            <br> &nbsp; &nbsp;at Layer.handle [as handle_request] (C:\Users\Ove\WebstormProjects\Vidley\node_modules\express\lib\router\layer.js:95:5)
            <br> &nbsp; &nbsp;at next (C:\Users\Ove\WebstormProjects\Vidley\node_modules\express\lib\router\route.js:137:13)
            <br> &nbsp; &nbsp;at Route.dispatch (C:\Users\Ove\WebstormProjects\Vidley\node_modules\express\lib\router\route.js:112:3)
            <br> &nbsp; &nbsp;at Layer.handle [as handle_request] (C:\Users\Ove\WebstormProjects\Vidley\node_modules\express\lib\router\layer.js:95:5)
            <br> &nbsp; &nbsp;at C:\Users\Ove\WebstormProjects\Vidley\node_modules\express\lib\router\index.js:281:22
            <br> &nbsp; &nbsp;at param (C:\Users\Ove\WebstormProjects\Vidley\node_modules\express\lib\router\index.js:354:14)
            <br> &nbsp; &nbsp;at param (C:\Users\Ove\WebstormProjects\Vidley\node_modules\express\lib\router\index.js:365:14)
            <br> &nbsp; &nbsp;at Function.process_params (C:\Users\Ove\WebstormProjects\Vidley\node_modules\express\lib\router\index.js:410:3)
            <br> &nbsp; &nbsp;at next (C:\Users\Ove\WebstormProjects\Vidley\node_modules\express\lib\router\index.js:275:10)
        </pre>
    </body>
</html>

有人可以向我解释一下这是怎么回事吗?只有DELETE端点会这样,其他所有都很好

1 个答案:

答案 0 :(得分:1)

Express通过您的处理程序(req, res),而不是(res, req),因此您的req实际上是res,并且没有.params字段。