我正在开发一个简单的应用程序,使咨询后端的NodeJS。一切都在本地主机上运行得很好,但是当我在我的ip地址(192.168.1.x)上运行angular服务器时,它就不再工作了。它在'http://localhost:3000/api/article‘上运行的nodeJS REST api和https://192.168.1.x:4200中的Angular服务器。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}`);
}
}我已经尝试了一些标志测试,我意识到它从来没有进入订阅(),我是新的,这是我第一次在我现在的ip上运行服务器,而不是在本地主机上。所以,如果我不能像这种情况或其他情况那样在后端请求,我就不会。
通过使用nodeJS REST api中的morgan和postman,我发现get请求在这一端可以正常工作。
如果有人能帮我,那就太可怕了。
发布于 2020-07-15 01:20:03
我完全不理解你的Angular服务器,但都表明你的Angular服务器无法看到你的localhost:3000。这就像您在另一台服务器上部署spa一样。该服务器不知道您的本地主机,您必须将您的API_URI (使用environments.ts)替换为您的后端所在的IP或域名:
例如,我的environment.prod.ts中有以下内容:
export const environment = {
production: true,
apiUrl: 'https://urltothenodejsbackend/api',
apiVersion: '/v1'
};https://stackoverflow.com/questions/62900323
复制相似问题