You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python向Node.js服务器发送POST请求数据未接收的问题解决

问题原因

你的Node.js服务器配置了express.json()中间件,这个中间件只会解析Content-Type为application/json的请求体。但你当前的Python代码使用requests.post的data参数传递JSON字符串时,请求的Content-Type默认是application/x-www-form-urlencoded,导致服务器的JSON解析中间件无法识别,所以req.body为空。

修复方案

有两种简单的修复方式:

方法一:使用json参数(推荐)

requests库提供了json参数,直接传入Python字典即可,它会自动将字典序列化为JSON字符串,并设置正确的Content-Type请求头:

import requests

API_ENDPOINT = "http://127.0.0.1:5000/api/server"
  
data = {"test": "testing"}

response = requests.post(url=API_ENDPOINT, json=data)

print(response)

方法二:手动设置请求头

如果坚持使用data参数传递JSON字符串,需要手动添加Content-Type: application/json请求头:

import requests

API_ENDPOINT = "http://127.0.0.1:5000/api/server"
  
data = '{"test": "testing"}'
headers = {"Content-Type": "application/json"}

response = requests.post(url=API_ENDPOINT, data=data, headers=headers)

print(response)
验证

修改后重新运行Python代码,Node.js服务器的console.log(req.body)就能正确输出{ test: 'testing' }了。

内容的提问来源于stack exchange,提问作者seriously

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.30 00:24:57