使用订阅功能从angular7中的节点获取空响应

时间:2019-05-28 08:01:25

标签: javascript node.js angular mean-stack

router.post('/login', function (req, res) {
  let username = req.body.username;
  let password = req.body.password;
  console.log(username, "===> username");
  console.log(password, "===> password");

      User.findOne({
        username: req.body.username,
        },function (err, user) {
        if (err) {
          res.status(502).send({
            "Message": "Db error",
            "error": err
          });
          console.log("login if");
        }
        //console.log("log",user)
            if (user) {
              if (user.username === req.body.username && user.password == req.body.password) {
                    var token = jwt.sign({
                      username: req.body.username,
                    },process.env.SECRET_KEY, {
                        expiresIn: parseInt(process.env.EXPIRY_TIME)
                      });
                    res.send({
                      Message: "logged in sucessfully",
                      Token: token
                    })
              }
            } else {
                res.status(404).send({
                Message: "not found",
                })
              }
      });

});

//以上代码是服务器端的代码,它向邮递员发送响应,还向客户端发送true,但不能发送对象
//下面的代码是login.component.ts文件

 login() {
     this.loginservice.authenticate(this.username, this.password)
        .subscribe((res) => {
              console.log(" user is",res);
              localStorage.setItem("user",res.toString());
                this.router.navigate(['dashboard']);
            }, (error) => {
              console.log(error);
            });
}

//,最后一个代码已启用   authenticate(用户名,密码){

  const url = environment.binanceserver + '/users/login';
    console.log("Endpoint being hit", url, username, password);
    const obj = {
      "username": username,
      "password": password
    }
    return this.http.post(url, obj);

1 个答案:

答案 0 :(得分:0)

您需要从服务器端启用CORS才能接受来自其他来源的请求。您可以使用cors在Express / Node中启用CORS。