我是TS的新手所以我不知道为什么会出现这种错误
VanillaJS版本工作得很好。 将其转移到TypeScript。 错误在我的index.ts中。 使用tsc命令编译TS代码仍然是相同的。 如果我在构造函数()中使用console.log(this.server)正常输出对象 但是当我在theListening()上使用console.log(this.server)时,它说未定义它很奇怪。
app.ts文件
import * as express from 'express'
import * as http from 'http'
import * as bodyParser from 'body-parser'
import * as cookieParser from 'cookie-parser'
import * as path from 'path'
import indexRoutes from './routes/index'
import userRoutes from './routes/users'
class App {
public express
constructor () {
this.express = express()
this.middleware()
this.mountRoutes()
this.errorHandler()
}
private middleware(): void {
this.express.use(bodyParser.json())
this.express.use(bodyParser.urlencoded({ extended: false }))
this.express.use(cookieParser())
this.express.use(express.static(path.join(__dirname, 'public')))
}
private mountRoutes(): void {
this.express.use('/', indexRoutes)
this.express.use('/users', userRoutes)
}
private errorHandler(): void {
this.express.use((req, res, next) => {
let err:any = new Error('Not Found') // I don't know why the err var needs the :any type to work with err.status below it. Without the :any type err.status is spitting errors hahaha
err.status = 404
next(err)
});
this.express.use((err, req, res, next) => {
res.locals.message = err.message
res.locals.error = req.app.get('env') === 'development' ? err : {}
res.status(err.status || 500)
res.json({
message: 'Error'
})
})
}
}
export default new App().express
index.ts文件
import app from './app'
import * as debug from 'debug'
import * as http from 'http'
class Server {
public server
public port
public debug
constructor () {
this.debug = debug('myexpress:server')
this.port = this.normalizePort(process.env.PORT || '3000')
app.set('port', this.port)
this.server = http.createServer(app)
this.server.listen(this.port)
this.server.on('error', this.onError)
this.server.on('listening', this.onListening)
}
private normalizePort(val): any {
let port = parseInt(val, 10)
if (isNaN(port)) {
return val
}
if (port >= 0) {
return port
}
return false
}
private onError(error): void {
if (error.syscall !== 'listen') {
throw error
}
let bind = typeof this.port === 'string' ? 'Pipe ' + this.port : 'Port' +
this.port
switch (error.code) {
case 'EACCES':
console.error(bind + ' requires elevated privileges')
process.exit(1)
break
case 'EADDRINUSE':
console.error(bind + ' is already in use')
process.exit(1)
break
default:
throw error
}
}
public onListening(): void {
let addr = this.server.address() << THIS RIGHT HERE
let bind = typeof addr === 'string' ? 'pipe ' + addr : 'port ' +
addr.port
debug('Listening on ' + bind)
}
}
new Server()
答案 0 :(得分:1)
首先,当使用.on(侦听器)将您的方法绑定到正确的范围时。
this.server.on('listening', this.onListening.bind(this))
或
this.server.on('listening', (e) => this.onListening(e))