【发布时间】:2021-01-01 10:50:52
【问题描述】:
我正在尝试学习后端和前端,到目前为止我还不错。但是现在我有一个问题。
在我使用 Express 的后端中,我使用 res.cookie 发送 cookie,如下所示
auth.js (/auth 路由)
const register = asyncErrorWrapper(async (req, res, next) => {
const {name, email, password} = req.body;
const user = await User.create({
name,
email,
password
});
sendJwtToClient(user, res);
});
tokenHelper.js
const sendJwtToClient = (user, res) => {
// user modeline gore jwt olusturma
const token = user.generateJwtFromUser();
const {JWT_COOKIE, NODE_ENV} = process.env;
return res
.status(200)
.cookie('access_token', token, {
httpOnly:true,
expires: new Date(Date.now() + parseInt(JWT_COOKIE) * 1000 * 60),
secure: NODE_ENV === 'development' ? false : true
})
.json({
success: true,
access_token: token,
data: {
name: user.name,
email: user.email
},
message: 'Your registration is succesful!'
});
};
然后我在与 Auth Service 连接的 register.component 中收到 Angular 应用程序的响应
来自Register.component
registerUser() {
this.sendButton.nativeElement.disabled = true;
this._authService.registerUser(this.user).subscribe(
res => {
if(res.status === 200) {
console.log(res);
}
}, err => {
console.log(err);
this.showError.nativeElement.className += ' alert alert-danger';
this.errMessage = err.error.message;
this.sendButton.nativeElement.disabled = false;
})
}
认证服务
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
@Injectable({
providedIn: 'root'
})
export class AuthService {
_registerURI = 'http://localhost:3000/auth/register';
_loginURI = 'http://localhost:3000/auth/login';
constructor(private http: HttpClient) { }
registerUser(user) {
return this.http.post<any>(this._registerURI, user, {observe: 'response'});
};
loginUser(user) {
return this.http.post<any>(this._loginURI, user, {observe: 'response'});
};
};
当我点击注册按钮时,我得到了这个响应:response
顺便说一句,我在后端使用 cors 包。提前致谢。
我还可以共享其他代码,任何您想要的页面。我只是觉得这样就够了。
【问题讨论】:
标签: node.js angular express cookies