【问题标题】:How to make a POST request with two arguments (MERN Stack)如何使用两个参数发出 POST 请求(MERN 堆栈)
【发布时间】:2021-04-04 10:54:39
【问题描述】:

我通常会尽量避免问这种基本的问题,但是,我花了一些时间试图弄清楚这一点,但无法提出任何问题。 我是使用 MongoDB 和 Mongoose 以及 Express 的新手,请见谅。

我正在制作一个在 MongoDB 中存储用户配置文件的应用程序,并在 Express 中创建一个 API 方法,允许用户编辑他们的配置文件。我正在使用 Mongoose 的 findByIdAndUpdate(),它有两个参数,第一个是用户的 '_id',第二个是带有新信息的对象。

这就是我在 Node 中编写函数的方式:

// Edit user profile API
exports.edit = (req, res) => {
  UserProfile.findByIdAndUpdate(req.body.id, {
      firstName: req.body.firstName,
      lastName: req.body.lastName,
      phone: req.body.phone,
      bio: req.body.bio,
    }), {
      new: true
    },
    (err, model) => {
      if (err) {
        console.log('Error: ', err);
      } else {
        console.log('Success:', model);
      }
    };
};

这就是我尝试使用 POSTMAN 发出请求以进行测试的方式:

请求卡在无限渲染上。 主要是,我只是不确定如何在 Express 中获取 ID。

非常感谢。

【问题讨论】:

  • 发送请求与调用函数不同。阅读该端点代码 - 它从请求的主体中获取五个道具(可能期望 JSON,但可能是格式编码或其他东西),并使用 them 制作两个参数来调用该函数。跨度>

标签: node.js mongodb express mongoose postman


【解决方案1】:

Node.js 期望 id 参数位于 req.body 对象中。所以你的邮递员请求正文应该是这样的

{
  "id": "your id",
  "firstName": "firstname",
  "lastName": "lastname",
  "phone": "phone",
  "bio": "bio"
}

将 ids 作为 url 参数传递也是一个好习惯。

In that case your postman would look like this:

您的 node.js 代码将如下所示:

exports.edit = (req, res) => {
  UserProfile.findByIdAndUpdate(req.params.id, {
      firstName: req.body.firstName,
      lastName: req.body.lastName,
      phone: req.body.phone,
      bio: req.body.bio,
    }), {
      new: true
    },
    (err, model) => {
      if (err) {
        console.log('Error: ', err);
      } else {
        console.log('Success:', model);
      }
    };
};

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-11-28
    • 2021-12-09
    • 2017-09-13
    • 2015-03-05
    • 1970-01-01
    • 2018-10-08
    • 1970-01-01
    相关资源
    最近更新 更多