我想打电话叫authenticationService.authenticateUser另一个类的内部函数,它只是返回的属性未定义,我不明白为什么。也许我OOP的知识欠缺,但我找不到任何地方这样的解释。这是我的路由器的NodeJS工作正常。
import * as express from "express";
import { Router, Request, Response, NextFunction } from 'express';
import * as shell from 'shelljs';
import { MongoClient } from'mongodb';
import * as bcrypt from 'bcryptjs';
import { DNSController, IpDataInterface } from '../../controllers/dns.controller';
const dnsController: DNSController = new DNSController()
export const MainRouter = (app: express.Application, authenticationService: any) => {
app.get('/', (req: Request, res: Response, next: NextFunction) => {
});
app.get('/ip-info', (req: Request, res: Response, next: NextFunction) => {
new Promise((resolve, reject) => {
dnsController.getIpData(resolve, req);
})
.then(
(data: IpDataInterface) => { res.status(200).send(data); }
)
.catch((err) => { res.status(500).send(); })
});
app.post('/login', (req: Request, res: Response, next: NextFunction) => {
console.log(req.body);
console.log(authenticationService);
authenticationService.authenticateUser(res, req.body);
})
}
这是我想达到的服务。
import * as bcrypt from 'bcryptjs';
import * as jwt from 'jsonwebtoken';
import { LocatorService } from '../database/locator.service';
import { UserInterface } from "../../dependencies/index";
// BcryptJS Salt
const salt = bcrypt.genSaltSync(10);
const tokenExp = 60 * 60;
export class AuthenticationService {
constructor(
private locatorService: LocatorService
) {
}
authenticateUser = (res: any, loginData: UserInterface) => {
console.log('running');
new Promise((resolve, reject) => {
this.locatorService.findThisOne(resolve, 'users', 'email', loginData.userName)
})
.then(
(userData: UserInterface) => {
if( userData.userName === loginData.userName && bcrypt.compareSync(loginData.password, userData.password)) {
//then send a jwt to the user that will be saved locally
const token = jwt.sign({ 'id': userData._id, 'role': userData.role }, 'shhhhh', { expiresIn: 60*60 });
res.statusMessage = "Login Successful";
res.status(200).send({ 'token': token, 'role': userData.role });
console.log("User: " + loginData.userName + "\nAuthenticated ; Status: " + res.statusCode + "\nToken Issued");
} else{ res.statusMessage = 'Access Denied'; res.status(401).send(); }
},
(err) => { res.status(500).send(); }
)
.catch((err) => { res.statusMessage = "Account Doesn't Exist"; res.status(401).send(); })
}
我们需要确保类AuthenticationService
类在实际情况下的主路由器模块在使用它之前。确保试图调用new AutheticationService( new LocatorService())
方法之前,你在呼唤像authenticateUser