【发布时间】:2020-02-29 07:04:31
【问题描述】:
当我在我的 Express POST 路由响应中使用 res.json() 时,一切正常。当我将响应更改为res.cookie() 时,遇到MongoDB 11000 Dup Key Error,出现以下奇怪行为:
- 文档正确保存到 MongoDB,但
POSTXHR 调用似乎有问题,因为浏览器控制台显示POST . . . - - ms,而通常它以毫秒为单位显示一个数字,即POST . . . -32 ms(即使它仍然显示200代码)。 - 过了一会儿,经过一段延迟后,我收到了
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;
}
有什么想法吗?谢谢!!
【问题讨论】: