【问题标题】:Frontend and backend can't communicate前端和后端无法通信
【发布时间】:2017-10-07 23:11:15
【问题描述】:

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

服务方式:

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

【问题讨论】:

  • 我觉得JSON.stringify的第二个参数http.post是没有必要的。此外,您可以在浏览器的开发者工具中打开“网络”选项卡并查看请求详细信息以了解失败的原因
  • 删除 JSON.stringify 并不能修复错误。此外,我在网络选项卡中根本看不到我的帖子请求。我什至添加了HttpHeaders 对象作为我的请求的标头Content-Type: application/json,但这也没有解决错误。
  • 可能您在网络标签中启用了一些过滤器,在不同的浏览器中查看

标签: angular koa2 domexception


【解决方案1】:

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

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

【讨论】:

    猜你喜欢
    • 2021-06-18
    • 1970-01-01
    • 2021-06-24
    • 2017-12-23
    • 2020-08-15
    • 2022-01-20
    • 1970-01-01
    • 1970-01-01
    • 2018-02-19
    相关资源
    最近更新 更多