简体   繁体   English

在 TypeScript 中使用全局变量 - Node Express

[英]Using Global Variable in TypeScript - Node Express

Using typescript in node express.在节点快递中使用 typescript。 Having problems of using global variable.使用全局变量时遇到问题。 Want to use the same global array variable tokenList:tokList in the imported module, current module and middleware.想要在导入的模块、当前模块和中间件中使用相同的全局数组变量 tokenList:tokList。 Tried lot of ways its not working How can i do it?尝试了很多方法它不起作用我该怎么做?

Provided my apirouter file below.在下面提供了我的 apirouter 文件。 Want to use variable tokenList:tokList in current apirouter file and in imported users.ts file and in tokenchecker.js middleware.想要在当前 apirouter 文件和导入的 users.ts 文件和 tokenchecker.js 中间件中使用变量 tokenList:tokList。

import express from 'express';
import { permissionsRoute } from './permissions';
import { rolesRoute } from './roles';
import { usersRoute } from './users';
import usersList from '../../mocks/users.json';

// import config from  './config.json';


const jwt = require('jsonwebtoken');  
const config = require('./config');
//const config = require('./config');
//const tokenList:any[]=new Array();
// interface TokenResponse {
//     status: string;
//     token: string;
//     refreshToken :string;
//   }

interface tokList {
    [key: string]: any;
}

var tokenList:tokList=[];
// using the middleware below
apiRouter.use(require('./tokenChecker'))

Provided the middleware file tokenChecker.js below下面提供了中间件文件tokenChecker.js

const jwt = require('jsonwebtoken')
const config = require('./config')

module.exports = (req,res,next) => {
  const token = req.body.token || req.query.token || req.headers['x-access-token']
  // decode token
  if (token) {
    // verifies secret and checks exp
    jwt.verify(token, config.secret, function(err, decoded) {
        if (err) {
            return res.status(401).json({"error": true, "message": 'Unauthorized access.' });
        }
      req.decoded = decoded;
      next();
    });
  } else {
    // if there is no token
    // return an error
    return res.status(403).send({
        "error": true,
        "message": 'No token provided.'
    });
  }
}

users.ts typescript file below users.ts typescript 文件如下

import express from 'express';
// @ts-ignore squash JSON compiler warning
import users from '../../mocks/users.json';

export const usersRoute: express.Handler = (_req, res) => {
  res.status(200).json(users);
};

Need to create a separate module for exporting variable.需要创建一个单独的模块来导出变量。 import into the modules that requires the global variable Thanks to jfriend00 comments导入到需要全局变量的模块中 感谢 jfriend00 的评论

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

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