无法从Express服务器向React传递数据的问题排查
React + Express + PostgreSQL 数据交互问题排查
前端(React)代码
const query = 'select * from "LabResults"'; const executeQuery = async () => { console.log('Running execute query') try { const response = await fetch(`/api/execute-query?query=${encodeURIComponent(query)}`); const result = await response.json(); console.log('Printing result fetched from DB ', response); } catch (error) { console.error('Error executing query:', error); } };
后端(Express)代码(server.js)
app.get(api_endpoint, async (req, res) => { try { // console.log(req); // const { query } = req.query; const query = 'SELECT * FROM "LabResults"'; if (!query) { return res.status(400).json({ error: 'Query parameter is required.' }); } const result = await pool.query(query); console.log(result.rows) const data = { message: 'Hello from the server!' }; res.send(data); } catch (error) { console.error('Error executing query 1:', error); res.status(500).json({ error: 'Internal Server Error' }); } }); app.listen(port, () => { console.log(`Server is running on http://localhost:${port}/${api_endpoint}`); });
遇到的问题
- 尝试从React向Express传递编码后的查询参数,服务器返回无效查询错误,求正确传递方式。
- 硬编码查询后,能从PostgreSQL获取数据并在服务器控制台打印,但返回给React时,用
res.send(data)、res.json(data)、res.send(JSON.stringify(data))都无效,React执行response.json()时抛出错误:SyntaxError: Unexpected token '<', "<!DOCTYPE "... is not valid JSON,模拟数据也报同样错误。
补充:服务器与客户端package.json
服务器端package.json
{ "name": "backend", "version": "1.0.0", "description": "", "main": "server.js", "scripts": { "test": "echo \"Error: no test specified\" && exit 1" }, "keywords": [], "author": "", "license": "ISC", "dependencies": { "@types/express": "^4.17.21", "express": "^4.18.2", "pg": "^8.11.3" } }
客户端(React)package.json
{ "name": "react-app", "version": "0.1.0", "private": true, "dependencies": { "@emotion/react": "^11.11.3", "@emotion/styled": "^11.11.0", "@fluentui/react": "^8.114.0", "@fluentui/react-hooks": "^8.6.34", "@mui/icons-material": "^5.15.1", "@mui/material": "^5.15.1", "@mui/x-data-grid": "^6.18.6", "@testing-library/jest-dom": "^5.17.0", "@testing-library/react": "^13.4.0", "@testing-library/user-event": "^13.5.0", "@types/jest": "^27.5.2", "@types/node": "^16.18.68", "@types/react": "^18.2.45", "@types/react-dom": "^18.2.18", "react": "^18.2.0", "react-dom": "^18.2.0", "react-scripts": "5.0.1", "typescript": "^4.9.5", "web-vitals": "^2.1.4" }, "scripts": { "start": "react-scripts start", "build": "react-scripts build", "test": "react-scripts test", "eject": "react-scripts eject" }, "eslintConfig": { "extends": [ "react-app", "react-app/jest" ] }, "browserslist": { "production": [ ">0.2%", "not dead", "not op_mini all" ], "development": [ "last 1 chrome version", "last 1 firefox version", "last 1 safari version" ] } }
问题解决方案
问题1:正确传递查询参数
- 取消后端代码中
const { query } = req.query;的注释,删除硬编码的const query = 'SELECT * FROM "LabResults"; - 前端已用
encodeURIComponent编码参数,Express会自动处理URL解码,可直接获取使用 - 关键提醒:直接接收前端传入的完整SQL查询存在严重SQL注入风险,推荐改为参数化查询,示例:
app.get('/api/execute-query', async (req, res) => { try { const { id } = req.query; if (!id) { return res.status(400).json({ error: 'ID parameter is required.' }); } // 参数化查询,避免SQL注入 const result = await pool.query('SELECT * FROM "LabResults" WHERE id = $1', [id]); res.json({ data: result.rows }); } catch (error) { console.error('Error executing query:', error); res.status(500).json({ error: 'Internal Server Error' }); } });
问题2:React解析JSON报错
该错误说明后端返回的不是JSON,而是React的404页面(HTML),核心原因是代理配置缺失:
- 在React的package.json中添加代理配置,指向Express服务器地址(假设Express运行在5000端口):
{ "name": "react-app", // ... 其他配置 "proxy": "http://localhost:5000" }
- 重启React开发服务器,确保Express和React运行在不同端口(比如Express在5000,React在3000)
- 确认后端
api_endpoint变量值为'/api/execute-query',避免路由不匹配返回404页面
另外,后端返回数据时优先使用res.json(),它会自动设置正确的Content-Type: application/json响应头:
res.json({ data: result.rows });
内容的提问来源于stack exchange,提问作者coolest-duck
相关产品推荐
相关产品推荐

