我无法从nodejs服务器将布尔值返回到我的角度服务

时间:2019-05-21 15:50:51

标签: node.js angular

我正在尝试使用angular进行登录,并希望返回一个表示我已登录的布尔值,但是即使我将其作为服务也不能返回它。

这是服务器代码

var loggedin = Boolean;
app.post('/auth', function(request,response){
var username = request.body.username;
var password = request.body.password;
console.log(username);
console.log(password);
if(username && password){
connection.query('SELECT * FROM accounts WHERE username = ? AND password = ?', [username,password], function(error,results,fields){
    if (results.length > 0){
        request.session.loggedin = true;
        request.session.username = username;
        // response.redirect('/home');
        console.log("Credentials are correct!")
        //res.send(result);
        loggedin = true;
        response.send(loggedin)
    } else{
        response.send('Incorrect login details!');
        console.log("Wrong credentials!")
        loggedin = false;
    }
    response.end();

});
} else {
    response.send('Please enter your username and or password');
    response.end();
}});

角度组件

export class LoginbarComponent implements OnInit {
  constructor(private modalService: NgbModal,private service:PostService{}

  Logres: Boolean = false;


  ngOnInit() {

  }

  private obj : any  = {"Email": "", "pass" : ""};
test(){

this.service.PostLogin(this.obj.Email,this.obj.pass);
console.log(this.obj.Email,this.obj.pass);

this.service.GetResponse().subscribe(logres =>{
  this.Logres=logres;
})}

角度服务

GetResponse(){
return this.http.get<Boolean>('http://localhost:3000/auth')}

完整的服务代码

    import { Injectable } from '@angular/core';
    import { HttpClient, HttpHeaders } from '@angular/common/http';
    import { DatabaseService } from './database.service';
    import { ForumPost } from './post';

    @Injectable({
      providedIn: 'root'
    })
    export class PostService {
      topics: string[] = [];
      threads: string[] = [];
      posts: PostService[] = [];


      GetTopic() {
        return this.http.get<String>("http://localhost:3000/gettopics")
      }

      Getthread(thread) {
        return this.http.get<String> 
       (`http://localhost:3000/getthread/${thread}`)
      }

      Getpost(post) {
        return this.http.get<ForumPost(`http://localhost:3000/getthread/${post}`)

      }

      GetResponse(){
        return this.http.get<Boolean>('http://localhost:3000/auth')

      }

      PostLogin(username,password){
        console.log("Username:" +username);
        console.log("Password:" +password);
         this.http.post("http://localhost:3000/auth",

         {"username":username,"password":password}).subscribe((data)=>{
        console.log(data)
      });
      }



  constructor( private http: HttpClient,
    private databaseService: DatabaseService) { 
  }
}


我添加了其余代码,以提供一些背景信息,而不必单独答复。

1 个答案:

答案 0 :(得分:0)

您可以将代码更改为此。因为您必须将数据返回给客户端

loggedin = true;
return res.send(loggedin);

如果还有问题,请告诉我