【问题标题】:Unable to update a request using a findOneAndUpdate in Mean Stack无法使用平均堆栈中的 findOneAndUpdate 更新请求
【发布时间】:2018-12-22 17:10:07
【问题描述】:

我想使用名为token 的字段发布请求。这是我的猫鼬模式

const UserSchema = mongoose.Schema({
  name: {
    type: String
  },
  email: {
    type: String,
    required: true,
    unique: true
  },
  username: {
    type: String,
    required: true,
    unique: true
  },
  password: {
    type: String,
    required: true
  },
  phone: {
    type: String
  },

  resetPasswordToken: {
    type: String
  },
  resetPasswordExpires: {
    type: Date
  }

});

这是我来自user.js的路线文件

router.put('/reset/:token', function(req, res) {
    console.log('listening');
    User.findOneAndUpdate(
        {resetPasswordToken:req.params.token},
        {
            password: req.body.password,
            resetPasswordToken: undefined,
            resetPasswordExpires: undefined
        },
        function(err,user) {
            if(err) {
                console.log(err + 'is here');
            } else {
                res.json(user);
            }
        }
    );
});

这是我发送 `POST 请求的地方。

resetPassword(passwordData) {
    let headers = new Headers();
    console.log(passwordData);
    headers.append('Content-Type','application/json');
    return this.http.put('http://localhost:3000/api/reset/'+passwordData.token,passwordData,{headers: headers})
    .map(res => res.json());
  }

没有采取任何行动我无法在我的 cmd 中看到 listening。对于用户,我已经将令牌值设为

"resetPasswordToken" : "2a287acacf7d5e98de9a158c8be82744ef0302f9"

我可以使用邮递员进行更新,但无法使用代码进行更新。

【问题讨论】:

    标签: node.js mongodb express mongoose mean-stack


    【解决方案1】:

    如果您能够处理邮递员而不是客户的请求,则有两种可能性:

    • CORS:在处理所有请求之前使用以下代码

      app.use((req,res,next)=>{ res.header("Access-Control-Allow-Methods", "GET, PUT, POST, DELETE"); next() })

    • 使用 x-http-method-override 标头:有时不允许放置或删除请求。 这可以在处理请求之前在客户端或服务器中发送时完成 (click here for the node module used)

    【讨论】:

    • 是的,我正在使用app.use(function(req, res, next) { res.header("Access-Control-Allow-Origin", "*"); res.header("Access-Control-Allow-Methods", "GET,HEAD,OPTIONS,POST,PUT"); res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept, Authorization"); next(); }); 但我仍然面临问题,我也尝试过使用我们的代码没有变化。请在您的代码中使用括号。
    • 使用方法覆盖标头
    • var methodOverride = require('method-override'); app.use(methodOverride()); 是的,我正在使用它们......
    • 在设置覆盖之后放置
    • 我该怎么做?你能描述一下吗?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-08-29
    • 2014-09-28
    • 2015-11-10
    • 1970-01-01
    • 2017-09-28
    • 2018-12-25
    • 2018-11-29
    相关资源
    最近更新 更多