【问题标题】:POST API body values coming through undefined?通过未定义的 POST API 正文值?
【发布时间】:2016-05-19 11:48:37
【问题描述】:

我正在使用 mongoose 在 MEAN 堆栈上构建一个 API。 API 应处理用户注册和身份验证。为了测试这一点,我使用 chrome 扩展程序 postman 向/signup 提交帖子请求。

app.use("/signup", bodyParser.urlencoded({ extended: false }));    
app.post("/signup", Auth.userExist, function (req, res, next) {
             if (!req.body.email || !req.body.password) {
                    res.json({success: false, msg: 'Please pass name and password.'});
                    console.log("email: " + req.body.email);
                    console.log("password: " + req.body.password);
                } else {
                    //do create new user logic...
                    res.json({success: true, msg: 'Successful created new user.'});
                }
});

您可以在此处看到我在向 API 的请求正文中发送的内容:

在控制台中,我得到了这个:

TypeError: 无法读取未定义的属性“电子邮件”

为什么我的请求正文没有通过?

【问题讨论】:

  • 你能说明你是如何将用户模型导入控制器的吗?
  • @BibekSubedi var User = require ('../api/public/user/model/userModel'); 在顶部
  • 保存回调是否正在执行?用户是否被保存到数据库?您是否尝试过 UserSchema.insert() 而不是 save()?
  • @tronman 我不这么认为。虽然,不确定它是否因为密码没有被散列而失败,或者它是否没有被尝试。我只是得到错误,而不是触发预方法。此外,插入没有任何区别
  • @tronman 请查看显示返回的错误消息的更新问题。

标签: javascript node.js rest authentication postman


【解决方案1】:

POSTMAN 中选择 x-www-form-urlencoded 而不是 form,然后传递表单值。您的代码应该可以正常工作。

【讨论】:

    【解决方案2】:

    尝试为您的端点配置正文解析器:

    var bodyParser = require("body-parser");
    
    app.use("/signup", bodyParser.urlencoded({ extended: false }));
    

    【讨论】:

    • hmmm,如果我这样做,我会得到“TypeError: Cannot read property 'email' of undefined” - 我只是将 app.use 直接放在路由类中的 app.post 上方,然后将 require 放在顶部。
    猜你喜欢
    • 2019-03-11
    • 1970-01-01
    • 2016-02-05
    • 2023-04-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多