【问题标题】:Angular9 http.get() doesn´t work properlyAngular 9 http.get() 无法正常工作
【发布时间】:2020-11-04 02:14:15
【问题描述】:

我正在开发一个简单的应用程序来咨询 NodeJS 的后端。一切都在本地主机上完美运行,但是当我在我的 IP 地址(192.168.1.x)上运行角度服务器时,它不再工作了。 它在“http://localhost:3000/api/article”和https://192.168.1.x:4200 中的 Angular 服务器上运行的 nodeJS REST api。 http.get 代码是这样的:

articles.component.ts:

import {ArticlesService} from '../../services/articles.service';
import {Article} from '../../models/article';
import { ViewChild } from '@angular/core'

@Component({
  selector: 'app-articles',
  templateUrl: './articles.component.html',
  styleUrls: ['./articles.component.scss'],
  providers: [ArticlesService],
  
})

export class ArticlesComponent implements OnInit {

  constructor(public articlesService: ArticlesService) { }

  article: Article;

  //Some other code that dosen't afect this

  getArticle(id: String) {
    this.articlesService.getArticle(id)
    .subscribe( res => {
      this.article = res as Article;
    })
  }

articles.service.ts:

import { HttpClient } from '@angular/common/http';

@Injectable({
  providedIn: 'root'
})
export class ArticlesService {

  readonly API_URI = 'http://localhost:3000/api/article';

  constructor(private http: HttpClient) { 
  }
  getArticle(id: String) {
      return this.http.get(this.API_URI+`/${id}`);
  }
}

我一直在尝试一些标志测试,我意识到它永远不会进入 subscribe(),我是新手,这是我第一次在我当前的 ip 上而不是在 localhost 上运行服务器。所以,如果在这种情况下或其他情况下我不能像这样在后端请求,我不会这样做。

在 nodeJS REST api 上使用 morgan 和 postman 我看到 get 请求在该端正常工作。

如果有人可以帮助我,那就太棒了。

【问题讨论】:

  • 如果您没有收到响应,则表示没有到达端点,这意味着您的 api 路由有问题(这表明资源不存在或 api 路由错误)。也可能是其他资源正在使用该端口,请检查开发工具中的网络选项卡并查看响应。

标签: node.js angular rest https httpclient


【解决方案1】:

我完全不了解 Angular 服务器,但所有这些都表明您的 Angular 服务器无法查看您的 localhost:3000。就像您将水疗中心部署在另一台服务器上一样。该服务器不知道您的本地主机,您必须将API_URI(使用environments.ts)替换为您的后端所在的IP或域名:

例如,我的 environment.prod.ts 中有这个:

export const environment = {
    production: true,
    apiUrl: 'https://urltothenodejsbackend/api',
    apiVersion: '/v1'
};

【讨论】:

  • 我试过了,还是不行,我的 Nodejs 后端在 http 上运行,Angular 在 https 上运行。会不会有问题?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-05-30
  • 2015-09-04
  • 2021-08-15
  • 1970-01-01
  • 2017-10-12
  • 1970-01-01
  • 2017-05-04
相关资源
最近更新 更多