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

如何将Python脚本返回的字符串发送至Node.js客户端并在网页展示

解决Python脚本发送的消息无法在Express+Socket.IO客户端展示的问题

问题原因

你的Express服务器没有配置JSON请求体解析中间件,无法解析Python脚本发送的JSON格式POST数据,导致req.body为undefined,进而req.body.msg出现未定义错误。

解决方案

1. 配置请求体解析中间件

Express 4.16.0及以上版本已内置express.json()中间件,无需额外安装依赖,直接在server.js中添加配置即可:

修改后的server.js代码:

var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);

// 添加JSON请求体解析中间件,解析后的数据挂载到req.body
app.use(express.json());

app.get('/', function(req, res){
  res.sendFile(__dirname + '/index.html');
});

app.post('/',function(req,res){
        var msg = req.body.msg;
        console.log("python result: " + msg);
        io.emit('message', msg);
        // 给Python脚本返回成功响应,避免请求挂起
        res.sendStatus(200);
 });

http.listen(3000, function(){
  console.log('listening on *:3000');
});

2. 关键修改说明

  • app.use(express.json()):启用中间件,自动解析Content-Type: application/json格式的请求体,解析后的数据会挂载到req.body上。
  • res.sendStatus(200):给Python的POST请求返回成功响应,避免请求长时间挂起。

3. 验证流程

  1. 重启Express服务器
  2. 执行Python脚本,服务器控制台会打印python result: test message
  3. 打开index.html页面,页面的message标签会实时展示收到的消息

确认Python脚本正确性

你的Python脚本已正确设置请求头并序列化JSON数据,无需修改:

import requests
import json

url = "http://localhost:3000"
data = {'msg': 'test message'}
headers = {'Content-type': 'application/json', 'Accept': 'text/plain'}
r = requests.post(url, data=json.dumps(data), headers=headers)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.17 10:17:22