简体   繁体   English

如何访问 serverMiddleware 中 Nuxt.config.js 中声明的 privateRuntimeConfig?

[英]How to access privateRuntimeConfig declared in Nuxt.config.js in serverMiddleware?

How to access configuration declared in privateRuntimeConfig in Nuxt.config.js file in serverMiddleware?如何访问 serverMiddleware 中 Nuxt.config.js 文件中 privateRuntimeConfig 中声明的配置?

$config and context are not available in serverMiddleware. $config 和 context 在 serverMiddleware 中不可用。

I am using serverMiddleware in Nuxtjs to write api.我在 Nuxtjs 中使用 serverMiddleware 来编写 api。

Its getting called however I am trying to pass some configuration from privateRuntimeConfig in Nuxt.config.js file.它被调用但是我试图从 Nuxt.config.js 文件中的 privateRuntimeConfig 传递一些配置。

const bodyParser = require('body-parser')
const app = require('express')()
const { uuid } = require('vue-uuid')
const productsModule = require('../lib/bal/products')

app.use(bodyParser.json())
app.post('/create', (req, res) => {
    console.log('Config:' + String(req))
    const result = productsModule.createProduct(this.$config, req.body.name, 'Trial product', '', 10, false, uuid.v1)
    if (result === undefined) {
        res.status(500).json({ error: 'Failed to create product. Try again!' })
        return
    }
    console.log(result)
    res.status(200).json(result)
})

module.exports = app

Yes you are right, since serverMiddleware only runs at service-side you can't use this.$config or context.$config.是的,你是对的,因为serverMiddleware只在服务端运行,你不能使用 this.$config 或 context.$config。 What i did is, if it is a static data, i use environment variables to call the data.我所做的是,如果它是 static 数据,我使用环境变量来调用数据。

.env file .env 文件

APP_USERNAME=M457ERCH1EF

serverMiddleware file ie xxx.js serverMiddleware 文件即 xxx.js

....
const username = process.env.APP_USERNAME
....

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM