簡體   English   中英

節點 JS 全局變量在調用后不起作用

[英]Node JS Global Variables is not working after call

我試圖在我的 controller 中調用我的全局變量,但我得到一個錯誤變量未定義。 請參閱下面的代碼供您參考。 希望能解決我的問題。 感謝你們

**服務器.js **

const serverConfig = require('./config/server.config')
const app = require('fastify')({ logger: true })
require('./models/response.model')
const mongoose = require('mongoose')
const conn = require('./config/monggo.config')
require('./routes/dbm.routes')(app)
const connect = async () => {
    try {
        await mongoose.connect(conn.uri)
        console.log('Connected to Mongoose!')
    } catch (error) {
        console.log(error)
    }
}

connect();
app.listen(serverConfig.port, '::', (err, address) => {
    if (err) {
        app.log.error(err)
        process.exit(1)
    }
    console.log('Listening at', address)
})

響應.model.js

module.exports = function () {

    global.successModel = {
        status: 'sucess',
        statusCode: 0,
        isSuccess: true,
        message: ''
    }
    global.failModel = {
        status: 'failed',
        statusCode: 1,
        isSuccess: false,
        message: 'Error encountered while processing request.'
    }
}

** monggo.controller.js **

exports.getProducts = async (req, res) => {
    //find Products in the databse
    Product.find({}, (err, product) => {
        //send error message if not found
        if (err) {
            res.send(err);
        }
        //else pass the Products
       
        res.send(successModel);
    })
    await res;
}

希望能解決我的問題。 謝謝

'./models/response.model'文件導出一個 function,您需要調用它來“安裝”您的全局變量。

- require('./models/response.model')
+ require('./models/response.model')()

作為建議,你應該避免使用全局變量,在 fastify 中你可以使用:

  • 裝飾器添加到您的app實例有用的數據,例如config s

另外,你的mongoose連接與Fastify無關,你可以封裝成一個插件來保證fastify在連接數據庫后啟動:

const fp = require('fastify-plugin')
app.register(fp(async function connect (instance, opts) {
  await mongoose.connect(conn.uri)
}))

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM