【问题标题】:Problems with res.cookie but not with res.jsonres.cookie 的问题,但 res.json 的问题
【发布时间】:2020-02-29 07:04:31
【问题描述】:

当我在我的 Express POST 路由响应中使用 res.json() 时,一切正常。当我将响应更改为res.cookie() 时,遇到MongoDB 11000 Dup Key Error,出现以下奇怪行为:

  1. 文档正确保存到 MongoDB,但 POST XHR 调用似乎有问题,因为浏览器控制台显示 POST . . . - - ms,而通常它以毫秒为单位显示一个数字,即 POST . . . -32 ms(即使它仍然显示200 代码)。
  2. 过了一会儿,经过一段延迟后,我收到了Dup Key Error,因为该路由似乎再次尝试保存文档。

我在前端或后端都没有其他控制台错误,根据控制台日志,cookie 的内容似乎没问题。

有什么想法吗?

模板

<form #f="ngForm" [formGroup]="userForm" (ngSubmit)="doSignUp(f)">
    <ng-container *ngFor="let key of keyArr; index as i"> 

    <label [hidden]='key[1]'> {{key[2]}}
      <div>
          <input *ngIf="key[1]==='password' type='password' [formControlName]='key[0]' id={{key[0]}} name={{key[0]}}/>
          <input *ngIf="key[1]!=='password' type='text' [formControlName]='key[0]' id={{key[0]}} name={{key[0]}}/>
      </div>
     </label>
    <br/>

    </ng-container>
    <button>Submit</button>

</form>

组件

doSignUp(f: NgForm) {
  this.member.postSignupForm(f).subscribe((res)=>console.log(`RES: ${JSON.stringify(res)}`));
}

授权服务(会员服务)

postSignupForm(f: NgForm): Observable<any> {
    return this.http.post(this.signup_url, f.value);
}

**快递POSTROUTE (https://localhost:3000/users/sign-up)

 . . . 
 . . . 
 user.save().then(()=> {
    res.json({"foo": "bar"} // EVERYTHING WORKS FINE. 
// IF, INSTEAD of res.json() I USE: res.cookie("SESSIONID", user.generateJWT(), {httpOnly:true, secure:true}); 
// then I get MONGODB DUP KEY ERROR as either front-end or back-end tries to save the same record a second time.

COOKIE 中间件

UserSchema.methods.generateJWT = function() {
    const today = new Date();
    const expirationDate = new Date(today);
    expirationDate.setDate(today.getDate() + 60);

    const thisJwt = jwt.sign({
        email: this["authData"].mainEmail.value[this["authData"].mainEmail.value.length-1],
        id: this._id,
        exp: parseInt(expirationDate.getTime() / 1000, 10),
    }, 'secret');
    console.log(`TOKEN: ${JSON.stringify(thisJwt)}`);
    return thisJwt;
}

有什么想法吗?谢谢!!

【问题讨论】:

    标签: angular express cookies


    【解决方案1】:

    在后端,在 res.cookie() 之后,我需要添加 res.send('done')。

     user.save().then(()=> {
        res.cookie("SESSIONID", user.generateJWT(), {httpOnly:true, secure:true});
        res.send('done');
     } 
    
    

    在前端,我需要将responseType 添加到POST 调用中:

    postSignupForm(f: NgForm): Observable<any> {
        return this.http.post(this.signup_url, f.value, {responseType: 'text'});
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-11-20
      • 2016-03-05
      • 1970-01-01
      • 2011-08-13
      • 1970-01-01
      • 2023-02-10
      • 1970-01-01
      • 2013-02-04
      相关资源
      最近更新 更多