前端JS发送POST请求后,Node.js/Python后端如何获取请求参数?
如何在Node.js Express和Python asyncio后端中获取前端POST的value值
前端代码修复
你当前的fetch请求直接传递对象作为body,但fetch默认会把对象序列化为[object Object]字符串,且自动设置Content-Type为text/plain,导致后端无法正确解析JSON格式数据。需修改为:
sendData() { let url = "http://localhost:9090/example"; fetch(url, { method: "POST", headers: { "Content-Type": "application/json" // 明确指定请求体为JSON格式 }, body: JSON.stringify({value: 10}) // 将JS对象转为JSON字符串 }) }
Node.js Express后端调整
你的Express代码已配置express.json()解析器,只需直接从req.body中提取value即可:
const express = require("express"); const cors = require('cors'); // 解决跨域问题(可选但推荐) const app = express(); const jsonParser = express.json(); app.use(cors()); // 允许跨域请求 app.use(express.static(__dirname + "/public")); app.listen(9090, function(){ console.log("Connection..."); }); app.post("/example", jsonParser, function(req, res){ const value = req.body.value; // 直接获取value值 console.log("Received value:", value); res.sendStatus(200); });
如果未安装cors,先执行命令安装:
npm install cors
Python asyncio后端调整
原生asyncio server需要手动解析HTTP请求,包括读取请求体内容。你当前仅读取了请求头部,需在读取完头部空行后,根据Content-Length读取请求体并解析JSON:
import asyncio import json async def test(reader, writer): headers = {} content_length = 0 # 读取并解析请求头部 while True: line = await reader.readline() if line == b'\r\n': break if line.startswith(b'Content-Length:'): content_length = int(line.decode().split(':')[1].strip()) # 读取请求体内容 body = await reader.read(content_length) # 解析JSON并提取value data = json.loads(body.decode()) value = data.get('value') print("Received value:", value) # 返回HTTP响应 response = b'HTTP/1.1 200 OK\r\nContent-Length: 0\r\n\r\n' writer.write(response) await writer.drain() writer.close() await writer.wait_closed() async def main(): server = await asyncio.start_server(test, '127.0.0.1', 9090 ) await server.serve_forever() asyncio.run(main())
内容的提问来源于stack exchange,提问作者Alex Corner
相关产品推荐
相关产品推荐

