我有一个简单的应用程序,它由nodejs,express和Typescript编写。但是在调用根路由时出现错误。服务器已成功启动,但是我找不到问题。我的代码:
server.ts
import app from "./app";
const PORT = 3001;
app.listen(PORT, () => {
console.log('Express server listening on port ' + PORT);
})
appRoutes.ts
import {Request, Response} from "express";
export class Routes {
public routes(app): void {
app.route('/')
.get((req: Request, res: Response) => {
res.status(200).send({
message: 'GET request successfulll!!!!'
})
})
}
}
app.ts
import * as express from "express";
import * as bodyParser from "body-parser";
import { Routes } from "./routes/appRoutes";
class App {
public app: express.Application;
public routePrv: Routes = new Routes();
constructor() {
this.app = express();
this.config();
this.routePrv.routes(this.app);
}
private config(): void{
// support application/json type post data
this.app.use(bodyParser.json());
//support application/x-www-form-urlencoded post data
this.app.use(bodyParser.urlencoded({ extended: false }));
}
}
export default new App().app;
然后我使用以下命令启动服务器:
npm run dev
哪个显示:
boolood@1.0.0开发人员P:\ boolood \ nodeversion
ts-node ./lib/server.ts
Express服务器在端口3001上侦听
有人可以帮助我解决这个问题吗?
答案 0 :(得分:0)
这不是答案,但是它将帮助您获取错误。
import { Request, Response } from "express";
export class Routes {
public routes(app): void {
app.route('/')
.get((req: Request, res: Response) => {
//res.status(200).send({
// message: 'GET request successfulll!!!!'
//})
// If request fails, throw an Error that will be caught
if (res.status < 200 || res.status >= 300) {
throw new Error('This request has failed ' + res.status);
}
// If everything went fine, return the response
else {
return res.json();
}
})
}
}