【问题标题】:Angular 2 how to define base URL forHttp requestsAngular 2如何为Http请求定义基本URL
【发布时间】:2017-08-03 05:23:11
【问题描述】:

我已经在我的应用程序中手动声明了http url。对于本地环境没问题,但是当它准备好部署到服务器上时,需要根据服务器主机进行更改。所以我需要一个解决方案来解决这个问题。

提前致谢!

【问题讨论】:

    标签: php laravel angular api


    【解决方案1】:

    我知道有两种方法

    1. 创建一个 env.js 文件并编写以下代码

        (function (window) {
      
         window.__env = window.__env || {};
      
        // API url
        window.__env.baseUrl = 'http://localhost:8080';
      
        // Base url
         window.__env.middleware = '/api/v1';
      
        // Whether or not to enable debug mode
        // Setting this to false will disable console output
        window.__env.enableDebug = true;
      }(this));
      
    2. 您使用我以前更喜欢的axios。它帮助我们管理标头并分离我们的 API 相关代码。示例:

      var axios = require('axios');
      var axiosApi = axios.create({
      
          baseURL: config.host,
      
          headers: {
      
         // "authorization": "Basic dXNlckBjbG9uZWN0LmNvbTpQYXNzQDEyMw==",
            "content-type": "application/json"
          },
        // withCredentials: true,
            auth: {
              username: config.user,
              password: config.password
            }
         })
      

    而 config.host、config.user 是 config.js 中根据您的环境类型声明的变量。

    【讨论】:

      猜你喜欢
      • 2016-04-03
      • 1970-01-01
      • 2016-05-30
      • 1970-01-01
      • 1970-01-01
      • 2017-11-15
      • 1970-01-01
      • 1970-01-01
      • 2017-07-14
      相关资源
      最近更新 更多