前端和后端无法通信



我正在使用 koa 框架编写一个全栈应用程序,在 node js 中用于后端,在 angular 4 中用于前端。问题是,当我通过前端在后端 API 上发出发布请求时(即当我想登录时),我收到一个 DOM 异常,其中包含文本"发生网络错误"和代码 19。后端本身工作正常(我已经用邮递员测试过)。以下是我的角度代码片段,其中包括我发出请求的服务方法和处理响应的组件方法。

服务方式:

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;
          }
    });
  }

组件方法:

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!');
      }
    });
  }

,你忘了在你的URL中指定协议,它应该是这样的:

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

最新更新