我想创建一个angular.io应用程序,但其余的API应从不同的服务器端口提供.
来自localhost:4200的Angular内容,来自node express服务器的数据在localhost:3000上独立启动.但是当我注入并使用'http'时,如何配置要使用的端口?
假设您正在使用Angular CLI搭建项目(我希望是这样),那么您应该已经可以访问其他环境设置。这些文件使您可以轻松地为应用程序提供值,该值可能会随其运行位置而变化。
environment.ts
提供环境值的接口,然后用environment.qa.ts
,environment.prod.ts
等等(您可以创建任意多个环境)来指定与该环境相对应的不同值。
假设您的环境文件中包含以下内容:
export const environment = {
myEndpoint: 'localhost:3000'
}
Run Code Online (Sandbox Code Playgroud)
您可以使用--env标志运行或构建应用程序以获取适当的值:
ng build --env=qa
Run Code Online (Sandbox Code Playgroud)
访问环境配置中定义的值很容易。在您的服务或组件中,只需为环境添加导入:
import { environment } from '../../environments/environment';
Run Code Online (Sandbox Code Playgroud)
然后使用值:
this.http.get(environment.myEndpoint)
Run Code Online (Sandbox Code Playgroud)
以某种方式获得"正确"URL的解决方案无效.
事实证明,这导致了一种情况,其中在休息服务器上看到http.put(...)作为OPTIONS请求.
Angular $ http发送OPTIONS而不是PUT/POST
通过从角度服务器代理到其余服务器,我找到了一种工作方式:
angular-cli服务器 - 如何将API请求代理到另一台服务器?
ng serve --proxy-config proxy.conf.json
Run Code Online (Sandbox Code Playgroud)
proxy.conf.json:
{
"/api": {
"target": "http://localhost:3000",
"secure": false
}
}
Run Code Online (Sandbox Code Playgroud)
Gün*_*uer -3
just add it to the url
this.http.get('http://localhost:3000')
Run Code Online (Sandbox Code Playgroud)