【问题标题】:Angular 6 API URL with port is not called correctly. API port dissapears on angular prod mode未正确调用带有端口的 Angular 6 API URL。 API 端口在 angular prod 模式下消失
【发布时间】:2020-05-26 18:07:34
【问题描述】:

我有一个 API URL,在我的 Angular 应用程序中设置为全局变量:

API_URL: 'http://52.109.53.23:3001'

我所有的 API 请求都通过这个 URL,它在开发模式 (ng s) 下工作正常,但是当我将它编译为生产 (ng build --prod) 并部署在我的 ubunut nginx Web 服务器上时,请求失败,他们错了,Api 端口号丢失:这是控制台输出:

Object { headers: {…}, status: 404, statusText: "Not Found", url: "http://52.109.53.23/auth/sign_in"

如果您发现端口消失了,我该如何解决这个问题?

【问题讨论】:

  • 这个值是通过environment类型设置获取的吗?很可能您只有 environment.ts 中的变量而不是 environment-prod.ts 中的变量,或者只是忘记了 prod 版本中的端口
  • @jcuypers 不,你能告诉我怎么做吗?我只是创建一个类(以 API_URL 作为缺点的 global.ts)并将其注入我创建的所有服务中。它在开发中工作正常,但是当我编译请求时没有端口号。

标签: angular nginx amazon-ec2 angular6


【解决方案1】:

根据官方文档。

ng build --prod

--prod 元标志使用以下构建优化功能。

  • 提前 (AOT) 编译:预编译 Angular 组件 模板。
  • 生产模式:部署启用的生产环境 生产模式
  • 捆绑:将您的许多应用程序和库文件连接到一个 几个捆绑包。
  • 缩小:删除多余的空格、cmets 和可选 令牌。丑化:重写代码以使用简短的、神秘的变量 和函数名
  • 死代码消除:删除未引用的模块和许多未使用的模块 代码。

环境配置在 angular-cli 配置文件(v6 中的 angular-cli.json 或 angular.json)中设置,默认有两个选项:dev 和 prod

"environments": {
  "dev": "environments/environment.ts",
  "prod": "environments/environment.prod.ts"
}

对于 v6+,angular.json 环境在配置部分进行配置。

"configurations": {
            "production": {
              "fileReplacements": [
                {
                  "replace": "src/environments/environment.ts",
                  "with": "src/environments/environment.prod.ts"
                }
              ],

如果您在两个环境中使用相同的 url,那么您应该在两个文件中定义它

src/environments/environment.ts

export const environment = {
  production: false,
  API_URL: 'http://52.109.53.23:3001'
};

src/environments/environment.prod.ts

export const environment = {
  production: true,
  API_URL: 'http://52.109.53.23:3001'
};

为了使用环境变量,您只需按如下方式导入环境对象:

import {environment} from '../../environments/environment';

....

apiUrl = environment.API_URL;

....

【讨论】:

    【解决方案2】:

    在您的项目中,您应该有一个文件夹“environments”,其中包含两个标准文件:environment 和 environment-prod.ts。在他们两个中你添加你需要的任何东西

    export const environment = {
       server : 'http://<ip>:<port>'
    }
    

    稍后你引用它

    import { environment } from '<wherever it is>';
    

    然后通过environment.server引用它

    当您执行产品构建时,将使用环境产品来支持环境

    【讨论】:

    • 在我的情况下服务器:'http://:',这样正确吗?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-11-17
    • 1970-01-01
    • 2019-01-02
    • 1970-01-01
    • 1970-01-01
    • 2020-07-05
    • 1970-01-01
    相关资源
    最近更新 更多