【问题标题】:Error using req.params in an express put route在 express put 路由中使用 req.params 时出错
【发布时间】:2021-03-21 15:33:04
【问题描述】:

我想使用我的 Ajax put 调用发送两个值作为参数。 taskID 是一个整数,taskCompleted 是一个布尔值。当 taskID 为两位数时(例如 12),我的 req.params 显示:

{ id: 1, completed: 2false }

下面是我的 Ajax 调用和 put 路由。我想了解如何发送参数,以便我的 taskID 和 taskCompleted 不会分开。

 $.ajax({
        method: 'PUT',
        url: '/list/' + taskID + taskCompleted
router.put( '/:id:complete', ( req, res ) =>{
    console.log( 'in router.put:', req.params );
    let queryString;
    if ( req.params.complete == 'true' ){
        queryString = `UPDATE "tasks" SET "completed" = false WHERE "id" = $1`;
    }else {
        queryString = `UPDATE "tasks" SET "completed" = true WHERE "id" = $1`;
    }
    pool.query( queryString , [req.params.id]).then( (results) =>{
        res.sendStatus( 200 );
    }).catch( (err) =>{
        res.sendStatus( 500 );
        console.log( err );
    })
})//end router.put

【问题讨论】:

    标签: javascript node.js ajax express


    【解决方案1】:

    您需要在路由的定义中用斜线分隔这两个值,即设为 router.put('/:id/:complete') 以使其工作。

    如果您将 completed 参数作为请求正文的一部分发送会更好,因为正文用于此目的,而 url 标识您要更新的资源。

    【讨论】:

      猜你喜欢
      • 2018-07-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-11-12
      • 1970-01-01
      • 2012-02-10
      相关资源
      最近更新 更多