Express自定义API端点无法接受POST请求该如何修复?
问题排查与修复方案
- 修复路由文件语法错误
你routes.ts中express后存在多余的点,直接导致路由实例创建失败,路由无法正常注册,修改为:
/* eslint-disable prettier/prettier */ import express from 'express'; import controller from './controller'; export default express .Router() .post('/enrich_profile', controller.enrich_profile) ;
- 确认路由前缀挂载逻辑
你需要将当前Profiling路由模块挂载到/api/v1/profile_data前缀下,才能匹配规范定义的完整端点路径,在项目入口/主路由文件中添加挂载代码即可:
// 路径替换为你实际的Profiling路由文件路径 import profilingRoutes from './controllers/profiling/routes'; app.use('/api/v1/profile_data', profilingRoutes);
- 修正Service层类型定义错误
你将enrich_profile的入参和返回值的data字段都定义为了never类型,该类型不允许接收任何实际值,会导致编译或运行时报错,根据业务调整类型即可,示例修改:
import L from '../../common/logger'; import { Request } from 'express'; interface Profiling { data: any; // 可替换为你实际的业务数据类型 } export class ProfilingService { enrich_profile(req: Request): Promise<Profiling> { // 通常业务逻辑只需取请求体,不需要完整req对象 console.log(req.body); L.info(`update user profile using \'${JSON.stringify(req.body)}\'`); const profile_data: Profiling = { data: req.body, }; return Promise.resolve(profile_data); } } export default new ProfilingService();
- 修正响应头拼接逻辑
你当前直接拼接返回对象r会导致location响应头出现[object Object]异常,需取对应字段拼接,示例优化controller代码:
import { Request, Response } from 'express'; import ProfilingService from '../../services/profiling.service'; export class Controller { async enrich_profile(req: Request, res: Response): Promise<void> { const r = await ProfilingService.enrich_profile(req); res .status(201) .location(`/api/v1/profile_data/enrich_profile/data/${r.data}`) .json(r); } } export default new Controller();
修改完成后重启服务,即可正常向POST /api/v1/profile_data/enrich_profile发起请求。
内容的提问来源于stack exchange,提问作者2Clutch
相关产品推荐
相关产品推荐

