Vue3调用Google Cloud Function出现CORS预检请求访问控制检查失败错误
问题根因
该CORS报错是浏览器发起的CORS预检OPTIONS请求未被Cloud Function正常响应导致:浏览器在发送正式POST请求前会先发送OPTIONS请求校验跨域权限,你的GCF没有专门处理该类请求,直接进入爬虫业务逻辑,返回了非200/204的状态码,因此触发校验失败。
修复步骤
1. 修复Cloud Function服务端代码
1.1 新增OPTIONS请求预处理逻辑
在所有业务逻辑之前优先处理预检请求,直接返回正确状态码,不走爬虫逻辑:
const puppeteer = require("puppeteer"); exports.webScrape = async (req, resp) => { resp.header("Access-Control-Allow-Origin", "*"); // 注意:如果不需要传递cookie等身份凭证,直接删除下一行,否则和Origin为*的配置冲突 // resp.header("Access-Control-Allow-Credentials", "true"); resp.header("Access-Control-Allow-Methods", "GET,HEAD,OPTIONS,POST,PUT"); resp.header( "Access-Control-Allow-Headers", "Origin,Accept, X-Requested-With, Content-Type, Access-Control-Request-Method, Access-Control-Request-Headers" ); // 新增:处理预检请求 if (req.method === 'OPTIONS') { return resp.status(204).send(''); } const input = req.body.input; async function scrapeSite(url) { //it does stuff here } try { const response = await scrapeSite(input); const data = JSON.stringify(response); resp.send(data); } catch (error) { console.log("server is catching the error"); console.log(error); resp.status(404).send({ ErrorMessage: "An invalid URL was given to the input box, please check the input and try again", error, }); } return; };
1.2 检查GCF权限配置
进入GCP控制台Cloud Function的触发器页面,确认你允许公开访问的接口已经给allUsers授予了「Cloud Functions 调用者」权限,否则OPTIONS请求会被权限层拦截返回403,同样会触发该报错。
2. 修复Vue客户端请求代码
Allow-Control-Allow-Origin是服务端返回的响应头,客户端请求不需要携带,直接删除该行即可,修正后的请求代码:
const response = await fetch(url, { method: "POST", mode: "cors", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ input }), }); // console.log(response); const data = await response.json();
验证方法
修改后重新发布GCF,清空浏览器缓存再发起请求,即可解决该CORS报错。
内容的提问来源于stack exchange,提问作者Gavin Coulson
相关产品推荐
相关产品推荐

