【问题标题】:Update user profile is not working when click the update button in Angular单击 Angular 中的更新按钮时更新用户配置文件不起作用
【发布时间】:2019-01-07 23:24:45
【问题描述】:

我们正在使用 Angular 和 Node.js Express。我们尝试从设置页面更新用户详细信息,但是当单击更新按钮时它会抛出:

加载资源失败:net::ERR_CONNECTION_RESET 似乎无法通过 observable 发送更新。当我在节点中检查这个 URL 时: http://localhost:3000/api/chatapp/user/edit-user 在浏览器中显示 {"message":"No Authorization"}。这是代码。

角度

  EditUser(body): Observable<any> {
    return this.http.post(`${BASEURL}/user/edit-user`, body);
  }

TS

private populateForm() {
    const unusedFields = [
      '_id',
    ...
    ...
    ];

    const userInfo = Object.assign({}, this.user);
    unusedFields.forEach((field) => delete userInfo[field]);
    this.SettingsForm.setValue(userInfo);
  }

  private buildSettingsForm() {
    this.SettingsForm = this.fb.group({
      email: [null, [Validators.required, Validators.email], this.forbiddenEmails],
      firstName: [null, [Validators.required, Validators.pattern('[a-zA-Z ]*')]],
      jobTitle: [null, [Validators.required]],
      lastName: [null, [Validators.required, Validators.pattern('[a-zA-Z ]*')]],
      username: [null, [Validators.required, Validators.pattern('(?=.*[a-z])(?=.*[A-Z])(?=.*[0-9])')]]
    });
    this.SettingsForm.setValidators(this.minimumAge(18));
  }

  UpdateUser() {
    this.usersService.EditUser(this.SettingsForm.value).subscribe(
      data => {
        console.log(data);
        this.router.navigate(['main']);
      },
      err => console.log(err)
    );
}

还有Node.js

async EditUser(req, res,next) {

User.findById(req.user.id, function (err, user) {

  if (!User) {
    return res
    .status(httpStatus.INTERNAL_SERVER_ERROR)
    .json({ message: 'User is not found' });
}

  const schema = Joi.object().keys({
    username: Joi.string()
      .min(4)
      .max(10)
      .required(),
    email: Joi.string()
      .email()
      .required(),
      firstName: Joi.string().required(),
      lastName: Joi.string().required(),
      jobTitle: Joi.string().required(),
  });

  const { error, value } = Joi.validate(req.body, schema);
  if (error && error.details) {
    return res.status(HttpStatus.BAD_REQUEST).json({ msg: error.details })
  }

const email = Helpers.lowerCase(req.body.email);
const username = Helpers.lowerCase(req.body.username);
const firstName = req.body.firstName;
const lastName = req.body.lastName;
const jobTitle = req.body.jobTitle;

User.email = email;
User.firstName = firstName;
User.lastName = lastName;
User.username = username;
User.jobTitle = jobTitle;

User.update()
});
} 
}

路由器

router.post('/user/edit-user', AuthHelper.VerifyToken, UserCtrl.EditUser);

MongoDb

    const userSchema = mongoose.Schema({
      username: { type: String },
      email: { type: String },
      isVerified: { type: Boolean, default: false },
      password: { type: String },
      passwordResetToken: String,
      passwordResetExpires: Date,
      firstName: { type: String },
      lastName: { type: String },
      jobTitle: { type: String },
...
...
module.exports = mongoose.model('User', userSchema);

我认为 Node.js 控制器和 Angular 函数都有问题。怎么了?我们如何解决这个错误?

【问题讨论】:

    标签: node.js angular mongodb express angular6


    【解决方案1】:

    您是否在请求中发送了令牌?!

    你忘记构建模式

        const userSchema = new mongoose.Schema({
          username: { type: String },
          email: { type: String },
          ...
       )}
    

    要捕获错误,您可以将回调作为参数传递给保存函数。

    user.save(function (err, updatedUser) {
        if (err) {
            /* Handle the error */
        };
     });
    

    您可以使用 set user.set({ [key]: value }); 而不是通过点符号直接访问,例如 user.firstname

    在你的情况下,它会像

    user.set({
            email: email,
            firstName: firstName,
            lastName: lastName,
            username: username,
            jobTitle: jobTitle
    })
    

    您的最终代码将是

    async EditUser(req, res, next) {
        User.findById(req.user.id, function (err, user) {
            if (!user) {
                return res
                    .status(httpStatus.INTERNAL_SERVER_ERROR)
                    .json({ message: 'User is not found' });
            }
            const schema = Joi.object().keys({
                username: Joi.string()
                    .min(4)
                    .max(10)
                    .required(),
                email: Joi.string()
                    .email()
                    .required(),
                firstName: Joi.string().required(),
                lastName: Joi.string().required(),
                jobTitle: Joi.string().required(),
            });
            const { error, value } = Joi.validate(req.body, schema);
            if (error && error.details) {
                return res.status(HttpStatus.BAD_REQUEST).json({ msg: error.details })
            }
            const email = Helpers.lowerCase(req.body.email);
            const username = Helpers.lowerCase(req.body.username);
            const firstName = req.body.firstName;
            const lastName = req.body.lastName;
            const jobTitle = req.body.jobTitle;
            user.set({
                email: email,
                firstName: firstName,
                lastName: lastName,
                username: username,
                jobTitle: jobTitle
            });
            user.save(function (error, updatedUser) {
                if (error) {
                    /* Handle it */
                }
            })
        });
    }
    

    您可以在 mongoose 文档中阅读更多信息以获取更多详细信息

    Update mongoose document

    注意,在 populateForm 方法中,您可以在不使用 delete 关键字的情况下过滤 unusedFields 数组上的对象

    【讨论】:

    • 我使用 AuthHelper.VerifyToken 来检查用户是否有权这样做。同时,其他操作也在工作,例如上传图片发布内容。只有在 EditUser 上面会抛出错误。
    • 我想您已经拦截了请求并将 Authorization: 'Bearer youreToken' 标头与它绑定。由于 EditUser 不响应 {"message":"No Authorization"},如果您使用旧的 http 你需要为每个请求设置头部 return this.http.post(${BASEURL}/user/edit-user, body, {headers: {'Authorization': Bearer ${token}}});
    • 如果对您来说不难,您可以通过复制您答案中的代码在上面我的问题的代码示例中进行解释吗?这样的 cmets 让人有些摸不着头脑。
    • 根据您的回答,您似乎解释了文档中的前 2 个选项。那么我应该在我的 Node.js 示例中删除哪些部分并从 user.set 开始?
    • 我应该用 user.update() 替换它还是我的代码的以上部分也必须删除?
    猜你喜欢
    • 1970-01-01
    • 2020-08-31
    • 2019-09-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-01-14
    • 1970-01-01
    相关资源
    最近更新 更多