TypeScript+Node.js项目Console.log无输出问题排查求助
问题描述
使用Visual Studio Code开发TypeScript+Node.js项目,服务器启动日志The server is running on port 6060可正常输出,但发送HTTP GET请求时,代码中添加的console.log调试日志(如"look 1""look 2"等)无法在终端显示。
相关代码文件
Routes.ts
/** source/routes/posts.ts */ import express from 'express'; import controller from '../controllers/posts'; const router = express.Router(); router.get('/posts', controller.getPosts); router.get('/posts/:id', controller.getPost); router.get('/posts?id=:id', controller.getPostID); router.put('/posts/:id', controller.updatePost); router.delete('/posts/:id', controller.deletePost); router.post('/posts', controller.addPost); export = router;
Posts.ts
import { Request, Response, NextFunction } from 'express'; import axios, { AxiosResponse } from 'axios'; interface Post { userId: Number; id: Number; title: String; body: String; } // getting all posts const getPosts = async (req: Request, res: Response, next: NextFunction) => { // get some posts console.log("look 1"); let result: AxiosResponse = await axios.get(`https://jsonplaceholder.typicode.com/posts`); let posts: [Post] = result.data; return res.status(200).json({ message: posts }); }; // getting a single post const getPost = async (req: Request, res: Response, next: NextFunction) => { // get the post id from the req let id: string = req.params.id; // get the post console.log("look 2"); let result: AxiosResponse = await axios.get(`https://jsonplaceholder.typicode.com/posts/${id}`); let post: Post = result.data; return res.status(200).json({ message: post }); }; //query a particular post const getPostID = async (req: Request, res: Response, next: NextFunction) => { // get the post id from the req //let id: string = req.query.id; let id: string = req.params.id; console.log("look 3"); // get the post let result: AxiosResponse = await axios.get(`https://jsonplaceholder.typicode.com/posts`,{ params: { id: 5 } }); let post: Post = result.data; return res.status(200).json({ message: post }); }; // updating a post const updatePost = async (req: Request, res: Response, next: NextFunction) => { // get the post id from the req.params let id: string = req.params.id; // get the data from req.body let title: string = req.body.title ?? null; let body: string = req.body.body ?? null; // update the post let response: AxiosResponse = await axios.put(`https://jsonplaceholder.typicode.com/posts/${id}`, { ...(title && { title }), ...(body && { body }) }); // return response return res.status(200).json({ message: response.data }); }; // deleting a post const deletePost = async (req: Request, res: Response, next: NextFunction) => { // get the post id from req.params let id: string = req.params.id; // delete the post let response: AxiosResponse = await axios.delete(`https://jsonplaceholder.typicode.com/posts/${id}`); // return response return res.status(200).json({ message: 'post deleted successfully' }); }; // adding a post const addPost = async (req: Request, res: Response, next: NextFunction) => { // get the data from req.body let title: string = req.body.title; let body: string = req.body.body; // add the post let response: AxiosResponse = await axios.post(`https://jsonplaceholder.typicode.com/posts`, { title, body }); // return response return res.status(200).json({ message: response.data }); }; export default { getPosts, getPost, getPostID, updatePost, deletePost, addPost };
Server.ts
/** source/server.ts */ import http from 'http'; import express, { Express } from 'express'; import morgan from 'morgan'; import routes from './routes/posts'; const router: Express = express(); /** Logging */ router.use(morgan('dev')); /** Parse the request */ router.use(express.urlencoded({ extended: false })); /** Takes care of JSON data */ router.use(express.json()); /** RULES OF OUR API */ router.use((req, res, next) => { // set the CORS policy res.header('Access-Control-Allow-Origin', '*'); // set the CORS headers res.header('Access-Control-Allow-Headers', 'origin, X-Requested-With,Content-Type,Accept, Authorization'); // set the CORS method headers if (req.method === 'OPTIONS') { res.header('Access-Control-Allow-Methods', 'GET PATCH DELETE POST'); return res.status(200).json({}); } next(); }); /** Routes */ router.use('/', routes); /** Error handling */ router.use((req, res, next) => { const error = new Error('not found'); return res.status(404).json({ message: error.message }); }); /** Server */ const httpServer = http.createServer(router); const PORT: any = process.env.PORT ?? 6060; httpServer.listen(PORT, () => console.log(`The server is running on port ${PORT}`));
排查结果与解决方案
核心问题
- 路由定义错误:
router.get('/posts?id=:id', controller.getPostID)不符合Express路由规则——查询参数(query)不需要在路由路径中定义,Express会自动解析req.query。这条路由永远不会被匹配,当发送/posts?id=xxx请求时,实际会被第一条/posts路由捕获执行getPosts;若此时也没看到look 1,大概率是请求路径不匹配或代码未正确编译。 - TypeScript编译缓存问题:修改后的代码(包括
console.log)可能未重新编译,服务器运行的仍是旧版本JS文件。
具体修复步骤
1. 修正路由逻辑
删除错误的路由定义,调整为支持查询参数的处理逻辑:
// 删掉这条错误路由 // router.get('/posts?id=:id', controller.getPostID); // 替换为:在/posts路由中根据query参数分发请求 router.get('/posts', (req, res, next) => { if (req.query.id) { return controller.getPostID(req, res, next); } return controller.getPosts(req, res, next); });
同时修正getPostID中id的获取方式,改为从req.query读取:
const getPostID = async (req: Request, res: Response, next: NextFunction) => { let id: string = req.query.id as string; // 从query获取传入的id console.log("look 3"); let result: AxiosResponse = await axios.get(`https://jsonplaceholder.typicode.com/posts`,{ params: { id: id // 使用请求传入的id,而非固定值5 } }); let post: Post = result.data; return res.status(200).json({ message: post }); };
2. 确保代码编译生效
- 检查
tsconfig.json的outDir配置,确认输出目录正确; - 删除编译输出目录(如
dist)后重新执行编译命令; - 若使用
nodemon等工具,确保配置了监听TS文件变化并自动编译重启。
3. 验证请求路径
确保发送的请求与路由匹配:
- 获取所有帖子:
GET http://localhost:6060/posts→ 终端应输出look 1 - 获取单条帖子(路径参数):
GET http://localhost:6060/posts/1→ 终端应输出look 2 - 获取单条帖子(查询参数):
GET http://localhost:6060/posts?id=5→ 终端应输出look 3
内容的提问来源于stack exchange,提问作者SUNDARAM SRIVASTAVA
相关产品推荐
相关产品推荐

