如何在 MEAN 堆栈应用程序中从后端到前端进行通信?

How to communicate from the back end to the front end in a MEAN stack application?

我是 MEAN 堆栈应用程序的新手,在尝试将数据从服务器发送到前端时遇到了一些问题。然而,我确实有一些沟通正在进行,但这似乎是我所能做的。在服务器中,我发送了 json 消息。

服务器

router.route("/users/register").post((req, res) => { 

registerLogin.findOne({ $or: [{ username }, { email }]}, (err, user) => {
        if (err)
            res.send(err);

        else if (!username || !email || !password)  
            res.status(403).json({ registerErrRequired: "Fill out whole form." });

前端

 registerUser(username, email, password)  {
    const user =  {
      username: username,
      email: email,
      password: password
    };
    return this.http.post(`${this.uri}/users/register`, user)
    .pipe(map(response => console.log(response)))

    .subscribe(() => { this.router.navigate(["/users/login"]) }, (errResp) => {

      errResp.error ? this.ngFlashMessageService.showFlashMessage({

        messages: [errResp.error.registerErrRequired], // Where json message gets caught and shown to the browser
      dismissible: true,
      timeout: false,
      type: 'danger'
      }) : console.log("An unkown error occured.");
    });
  }

这很好用,但我似乎无法 req/res 除了使用即显消息。我的问题是想以其他方式使用它,而不仅仅是 flash 消息。例如,如果用户没有会话,那么我希望他们导航回登录页面。这是我尝试但失败的方法。

服务器

// Middleware
const redirectLogin = ((req, res, next) => {
    if (!req.session.user) 
        res.status(401).json({ loggedIn: false });
    else
        next();
}); 
// Route
router.route("/home").get(redirectLogin, (req, res) => {
    Blog.find((err, docs) => {
        if (err)
        console.log(err);
    else
        res.json(docs);
    }); 
});

前端

homePage() {
  // Here is where I would like to say, If session, then true, else navigate(["/users/login"])
   if (loggedIn === false)
       this.router.navigate(["/users/login"])
   else
       // Success
  return this.http.get(`${this.uri}/home`);
}

我找到通信的唯一方法是通过发送错误提示消息,除此之外别无他法。

你可以做的是在 ngOnInit 生命周期挂钩中调用一个 api 来检查用户是否登录,所以每次你的组件加载时你都可以检查会话是否存在相应的后端和路由。

 export class App implements OnInit{
          constructor(){
             //called first time before the ngOnInit()
          }

          ngOnInit(){
           //CheckLogin() is a method in your service which calls your backend api
             this.http.post("your authentication url to check if session exits ",{username:username}).subscribe(data=>{
            if (data["loggedIn"] === false)

               this.router.navigate(["/users/login"])


        }) 
          }

}

Angular也有HTTP interceptors,你可以用jwt解决这个问题,http interceptors