【发布时间】:2019-12-01 06:13:46
【问题描述】:
我正在尝试使用 NodeJS 和 TypeScript 创建一个简单的应用程序 除了 Express 路由外,一切都运行良好。当我尝试执行获取请求时,请求不起作用,无法打印或发送任何内容。
这是我的主要代码
"use strict"
import bodyParser from "body-parser"
import express from "express"
import http from "http"
import io from "socket.io"
import cors from "cors"
import { Server as Main } from './interfaces/'
import { Routes } from "./lib/"
const server = new http.Server(express())
let host = `localhost`
const main: Main = {
port: process.env.PORT || 3000,
app: express(),
server, host,
socket: io(server, {origins:`${host}`})
}
class Server {
constructor(private main: Main) {
}
appConfig() {
this.main.app.use(cors())
//.all('*', apikey)
.use(bodyParser.json())
.use(bodyParser.urlencoded({extended:true}))
}
includeRoutes() {
const routes = new Routes(this.main.app,this.main.socket)
routes.routesConfig()
}
appExecute() {
this.appConfig()
this.includeRoutes()
const onListening = () => console.log(`Successful at port: ${this.main.port}`)
this.main.server.listen(this.main.port, onListening)
}
}
const app = new Server(main)
app.appExecute()
这里是路由文件
'use strict'
import { Request, Response } from "express"
import { Server as Main } from './../interfaces/'
export default class Routes {
constructor(private app: Main["app"], private socket: Main["socket"]) {}
appRoutes() {
console.log(this.app) //<-- this gives me data
console.log(this.app.get()) //<-- this also gives me data
this.app.get('/', (req:Request, res:Response) => {
console.log("test") // not printing
res.send("test") // not sending
})
}
routesConfig() {
this.appRoutes()
}
}
import Routes from './routes'
export {
Routes
}
好吧,我的接口文件
import { Application } from "express"
export default interface Server {
port: number|string,
host: string,
app: Application,
server: any
socket: any
}
如果我在路由文件中打印应用程序,它会给我来自 express 的所有信息,也是 get 方法,但是当我输入 http://localhost:3000/ 时不起作用,只需说 Cannot GET 并且不打印 console.logs
【问题讨论】:
-
在你的路由文件中,
nap = express()是什么? -
你能把
connsole.log(this.app.get())去掉吗? -
我认为你还没有在 Routes 构造函数中实例化你的
app。您应该创建一个新的 express 实例,然后调用它的 API。 -
@RinkeshGolwala,抱歉我已经删除了。我曾经检查过我将 express() 发送到路由文件的方式是否良好。
-
@JonasWilms,做到了,但没有任何改变。 “nn”是个错误。
标签: javascript node.js typescript express routes