当我在Express res.json()
路由响应中使用POST
时,一切正常。当我将响应更改为res.cookie()
时,遇到MongoDB 11000 Dup Key Error
,具有以下奇怪的行为:
POST
XHR调用似乎有问题,因为浏览器控制台显示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);
}
**表达POST
路线(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 MIDDLEWARE
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;
}
有什么想法吗?谢谢!!
答案 0 :(得分:0)
在后端,在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'});
}