【问题标题】:TypeError: Cannot destructure property id of req.params as it is undefinedTypeError:无法解构 req.params 的属性 ID,因为它未定义
【发布时间】:2020-04-04 15:02:04
【问题描述】:

我正在尝试从数据库中获取用户配置文件,并在运行配置文件 url (localhost:3000/Profile/1) 时将其作为 json 对象返回。但我收到此错误:TypeError: Cannot destruct property id of req.params 因为它未定义。

这是快递服务器中的代码。

const express = require('express');
const bodyParser = require('body-parser');
const bcrypt = require('bcryptjs');
const cors = require('cors');
const knex = require('knex');

const app = express();
app.use(cors());
app.use(bodyParser.json());


app.get('/Profile/:id', (res,req) =>{
    const {id} = req.params;
    db.select('*').from('user').where({id})
    .then(user => {
    res.json(user[0])})
})

我使用邮递员发送获取请求。

【问题讨论】:

  • req.params.id 会起作用的
  • console.log( req.params )app.get 中返回什么?
  • res 和 req 在你的函数中是错误的,它应该是 (req, res) => { ...
  • 事实证明@George 是对的,顺便说一句,这是我这边的愚蠢错误。我立即更改了 req 和 res,它起作用了。谢谢大家。特别感谢乔治。

标签: javascript node.js json express body-parser


【解决方案1】:

您将错误的参数传递给get 函数

例如

// respond with "hello world" when a GET request is made to the homepage
app.get('/', function (req, res) {
  res.send('hello world')
})

你的情况

app.get('/Profile/:id', (req, res) =>{
   console.log(req.params)
}

【讨论】:

    【解决方案2】:

    参数的顺序是Request,Response所以你必须这样做:

    app.get('/profile/:id', (request, response) => {
        const { id } = request.params;
        db.select('*').from('user').where({id}).then(
           user => {
               res.json(user[0])
           });
    });
    

    【讨论】:

      【解决方案3】:

      我看到你的错误,你输入了函数 (res, res) 并且应该是 (req,res)。

      【讨论】:

        猜你喜欢
        • 2021-10-20
        • 2020-10-07
        • 1970-01-01
        • 2021-03-08
        • 2021-05-11
        • 2021-04-04
        • 2021-08-30
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多