MySQL查询结果仅在控制台显示,Postman无返回问题求助
问题解决:Serverless-offline中MySQL查询结果无法返回至Postman
问题根源分析
- mysql模块不支持Promise调用:你的
db.js使用的是传统mysql模块,它的query方法是回调风格,无法直接用await等待异步结果。虽然控制台能打印出查询结果,但这是因为异步查询在函数返回后才执行完成,导致返回给Postman的result并非实际数据。 - 响应类型配置错误:
serverless.yml中设置responseType: 'text/plain',但你返回的是JSON格式字符串,Postman无法正确解析该类型的响应内容。
解决方案步骤
1. 改用mysql2的Promise版本
修改db.js,使用支持Promise的mysql2连接,确保能通过async/await正确等待查询结果:
const mysql = require('mysql2/promise'); const db = mysql.createConnection({ host: "localhost", port: 3307, user: "root", password: "", database: "nodejs_beers", }); // 初始化数据库连接 (async () => { try { await db; console.log("database connected"); } catch (err) { console.log(err.message); } })(); module.exports = db;
2. 修正handler中的查询逻辑
调整handler.js,正确获取mysql2的查询结果,并显式设置响应头为JSON类型:
const db = require('../db/db'); module.exports.getUsers = async (event) => { try { console.log("outside users"); // mysql2 promise的query返回[结果集, 字段信息],取第一个元素即可 const [result] = await db.query("SELECT * FROM beers"); console.log("outside users 1"); console.log({result}); return { statusCode: 200, headers: { 'Content-Type': 'application/json', }, body: JSON.stringify({ message: "Query executed successfully", data: result }), }; } catch (error) { console.log(error); return { statusCode: 500, headers: { 'Content-Type': 'application/json', }, body: JSON.stringify({ message: "An error occurred", error: error.message }), }; } };
3. 调整serverless.yml的响应类型
将响应类型改为JSON,匹配返回的内容格式:
plugins: - serverless-offline functions: read: handler: ./handlers/handler.getUsers events: - http: method: get path: /getUsers responseType: 'application/json'
验证操作
- 重启
serverless-offline服务 - 在Postman中发送GET请求到
http://localhost:3000/getUsers(端口根据你的配置调整) - 此时即可正常获取包含MySQL查询结果的JSON响应
内容的提问来源于stack exchange,提问作者Adel
相关产品推荐
相关产品推荐

