Google Cloud Function无法正常接收客户端传入参数问题求助
解决思路
- 优先处理CORS预检请求:浏览器发送
application/json类型的POST请求前,会自动发OPTIONS预检请求,你当前的云函数没有处理该类请求,会导致后续实际POST请求的参数传递失败,需要在函数入口新增OPTIONS请求的判断逻辑。 - 不要重复解析请求体:Google Cloud Function 会自动解析
Content-Type: application/json的请求体,你不需要手动对req.body.input做JSON.parse操作,重复解析反而会抛出异常得到undefined值,直接取req.body.input即可。 - 修正客户端请求头:
Allow-control-allow-origin是服务端响应头,不需要在客户端请求头里添加,多余的自定义头可能触发额外的预检规则,直接删除即可。 - 分层排查变量值:先在浏览器控制台查看客户端打印的
here is input ${input}日志,确认发送前input变量本身有值;再去Google Cloud Function的日志面板查看console.log(req.body)的输出,确认请求体是否正常传递到服务端。
修正后代码示例
Google Cloud Function 代码
/** * Responds to any HTTP request. * * @param {!express:Request} req HTTP request context. * @param {!express:Response} res HTTP response context. */ const puppeteer = require("puppeteer"); exports.webScrape = async (req, resp) => { // 统一设置CORS头 resp.set('Access-Control-Allow-Origin', '*') resp.set('Access-Control-Allow-Methods', 'GET, POST, OPTIONS') resp.set('Access-Control-Allow-Headers', 'Content-Type') // 处理预检请求 if (req.method === 'OPTIONS') { return resp.status(204).send('') } console.log('working woot woot') // 直接取input值即可,无需额外解析 const input = req.body.input console.log('收到的input值:', input) resp.send('hello world') };
客户端请求代码
try { this.$emit("loading", true); console.log("getting the scraper"); // 先确认这里的input变量有值 console.log(`here is input ${input}`); const response = await fetch( "myURL", { method: "POST", mode: "cors", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ input }), } ) // 后续处理响应逻辑 } catch (e) { console.error('请求出错:', e) }
内容的提问来源于stack exchange,提问作者Gavin Coulson
相关产品推荐
相关产品推荐

