Python 和 Node.js 之间通信 JSON 数据
warning:
这篇文章距离上次修改已过192天,其中的内容可能已经有所变动。
在Python和Node.js之间进行通信时,可以使用http
模块(Node.js)来创建一个服务器端点,并使用Python的requests
库来发送JSON数据。
Python端代码(使用requests
库):
import requests
import json
# 要发送的数据
data = {
'message': 'Hello from Python',
'type': 'greeting'
}
# Node.js服务器的URL
url = 'http://localhost:3000/receive'
# 发送POST请求
response = requests.post(url, json=data)
# 打印响应内容
print(response.text)
Node.js端代码(使用http
模块和express
框架):
const express = require('express');
const app = express();
const port = 3000;
app.use(express.json()); // Middleware for parsing JSON bodies
app.post('/receive', (req, res) => {
const jsonData = req.body;
console.log('Received data:', jsonData);
// 处理jsonData...
res.send('Data received');
});
app.listen(port, () => {
console.log(`Server listening at http://localhost:${port}`);
});
确保先运行Node.js服务器,然后运行Python客户端代码以发送数据。这个例子演示了如何在两个语言之间发送和接收JSON数据。
评论已关闭