angularkoa2domexception

Frontend and backend can't communicate


I'm writing a fullstack app using koa framework in node js for backend and angular 4 for frontend. The problem is that when I make a post request on backend API via frontend (i.e. when I want to sign-in) I get a DOM Exception with text "Network error occurred" and code 19. The backend itself works fine(I've tested it with postman). Here are snippets of my angular code that include the service method with which I make the request and the component method which handles the response.

Service method:

authenticate(username: string, password: string): Observable<boolean> {
    return this.http.post('localhost:3000/api/sign-in',
        JSON.stringify({ username: username, password: password }))

        .map((response: Response) => {
          let token = response.json().token;
          if (token) {
            this.token = token;
            localStorage.setItem('currentUser', JSON.stringify({ username: username, token: token}));
            return true;
          } else {
            return false;
          }
    });
  }

Component method:

logIn(): void {
    this.authenticationService.authenticate(this.username, this.password)
    .subscribe(result => {
      if (result == true) {
        this.router.navigate(['/people']);
      } else {
        console.log('Username or password incorrect!');
      }
    });
  }

Solution

  • Oh, you forgot to specify protocol in your URL, it should be something like:

    this.http.post('http://localhost:3000/api/sign-in', ...