【问题标题】:Load custom configuration runtime加载自定义配置运行时
【发布时间】:2019-10-20 16:25:48
【问题描述】:

我有一个nuxt 应用程序,我需要在应用程序首次启动时从生成的配置文件中附加数据。我在实际构建中不能这样做的原因是因为此时配置文件不存在;它是在通过引导脚本调用npm start 之前生成的。

为什么我不在启动应用程序之前生成配置文件,你可能会问,这是因为应用程序在 docker 容器中运行,并且构建的映像不能包含特定于环境的配置文件,因为它应该在不同的环境中使用,例如作为测试、登台和生产。

目前我正在尝试使用钩子来解决这个问题,但我不确定如何在应用程序中实际设置配置数据以便可以在任何地方使用:

# part of nuxt.config.js
  hooks: {
    listen(server, listener) {
      # load the custom configuration file.
      fs.readFile('./config.json', (err, data) => {
        let configData = JSON.parse(data));
      });
    }
  },

当应用程序第一次开始监听连接的客户端时,上面的钩子会被触发。不确定这是最好的,甚至是可能的方法。

我也尝试过使用插件来解决这个问题:

import axios from ‘axios’;

export default function (ctx, inject) {
  // server-side logic
  if (ctx.isServer) {
    // here I would like to simply use fs.readFile to load the configuration, but this is not working?
  } else {
    // client-side logic
    axios.get(‘/config.json’)
      .then((res) => {
        inject(‘storeViews’, res.data);
    });
  }
};

在上面的代码中,我在使用fs 模块和axios 时都遇到了问题。

我也在考虑使用中间件来执行此操作,但不确定如何进行。

【问题讨论】:

    标签: node.js vue.js plugins configuration nuxt.js


    【解决方案1】:

    如果其他人遇到这种问题,我最后想出的解决方案是:

    // plugins/config.js
    class Settings
    {
      constructor (app, req) {
        if (process.server) {
          // Server side we load the file simply by using fs
          const fs = require('fs');
          this.json = fs.readFileSync('config.json');
        } else {
          // Client side we make a request to the server
          fetch('/config')
            .then((response) => {
              if (response.ok) {
                return response.json();
              }
            })
            .then((json) => {
              this.json = json;
            });
           }
         }
    }
    
    export default function ({ req, app }, inject) {
      inject('config', new Settings(app, req));
    };
    

    为此,我们需要使用服务器中间件:

    // api/config.js
    const fs = require('fs');
    const express = require('express');
    const app = express();
    
    // Here we pick up requests to /config and reads and return the
    // contents of the configuration file
    app.get('/', (req, res) => {
      fs.readFile('config.json', (err, contents) => {
        if (err) {
          throw err;
        }
        res.set('Content-Type', 'application/json');
        res.end(contents);
      });
    });
    
    module.exports = {
      path: '/config',
      handler: app
    };
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-05-10
      • 2010-10-05
      • 2020-02-01
      • 2023-02-07
      • 1970-01-01
      • 1970-01-01
      • 2014-05-03
      • 1970-01-01
      相关资源
      最近更新 更多