Node.js+Express搭建FHIR Server时POST请求体接收为Undefined问题
Express FHIR Server POST请求体req.body为undefined的解决方法
我用Node.js和Express搭建FHIR Server,尝试通过POST请求创建Patient资源,但服务器始终收到undefined的请求体,换用Thunder Client和VS Code REST Client测试都存在这个问题。已做的排查包括:
- 确认JSON请求体格式正确,包含resourceType等必填字段
- 客户端Content-Type、Accept头已设为
application/fhir+json - 验证请求方法为POST、端点URL与路由匹配
- 排查客户端设置、重启服务器、查看日志均未发现异常
核心原因
Express默认不会自动解析请求体,且默认的express.json()中间件仅处理application/json类型的请求,而FHIR请求使用的是application/fhir+json类型,导致请求体未被解析,所以req.body为undefined。
解决方案
在Express应用中添加带类型配置的express.json()中间件,确保能解析application/fhir+json格式的请求体,且中间件要挂载在所有路由定义之前。
修改后的核心代码
const { VERSIONS } = constants; const express = require('express'); let config = { profiles: { patient: { service: './patient.service.js', versions: [VERSIONS['4_0_0']], }, }, }; let server = initialize(config); let logger = loggers.get('default'); // Create an Express application const app = express(); // 关键:添加解析application/fhir+json和application/json的中间件,放在路由之前 app.use(express.json({ type: ['application/json', 'application/fhir+json'] })); // In-memory data store for Patient resources const patientDataStore = []; // creating a Patient resource app.post('/4_0_0/Patient', (req, res) => { console.log('Received POST request with data:', req.body); console.log('Request headers:', req.headers); const patientData = req.body; console.log('Received POST request with data:', patientData); // Perform validation, data storage, etc. // For simplicity, we'll just push the patientData to the in-memory store patientDataStore.push(patientData); console.log('Patient data stored:', patientDataStore); // Send a response indicating success (HTTP status code 201 for resource creation) res.status(201).json({ message: 'Patient resource created successfully' }); }); // 其余路由和代码保持不变 app.get('/4_0_0/', (req, res) => { res.send('GET request to /4_0_0/'); }); app.get('/4_0_0/Patient', (req, res) => { console.log('Data in patientDataStore:', patientDataStore); res.json(patientDataStore); }); app.get('/patientData', (req, res) => { console.log('GET request to /patientData'); console.log('Data in patientDataStore:', patientDataStore); res.json(patientDataStore); }); const fhirMiddleware = (req, res, next) => { server(req, res, next); }; app.use('/fhir', fhirMiddleware); const PORT = 3000; app.listen(PORT, () => { logger.info(`Starting the FHIR Server at localhost:${PORT}`); });
注意事项
- 中间件的挂载顺序至关重要,必须在所有路由定义之前添加,否则路由处理时请求体还未被解析
- 如果后续还有其他类型的请求体需要解析(比如form-data),可以额外添加
express.urlencoded()等对应的中间件
内容的提问来源于stack exchange,提问作者legacyunlimited
相关产品推荐
相关产品推荐

