Flutter发送Post请求至Google Cloud Function时请求头丢失求助
问题分析
直接打印request.headers无法看到预期头的常见原因:Express框架会将HTTP头名标准化为小写;若为跨域请求,CORS配置未允许自定义头会导致请求头被过滤。
解决方案
1. 调整Cloud Functions端的头获取方式
不要直接依赖print(request.headers)的输出,改用框架方法或小写键获取头:
exports.send_to_queue = functions.https.onRequest((req, res) => { // 使用req.get()获取标准化后的头 console.log('Authorization:', req.get('Authorization')); console.log('Content-Type:', req.get('Content-Type')); // 或直接访问小写的头键 console.log('authorization:', req.headers.authorization); console.log('content-type:', req.headers['content-type']); // 后续业务逻辑 res.status(200).send('处理完成'); });
2. 优化Flutter端的请求代码
使用HttpHeaders类常量避免头名拼写错误,确保请求头设置准确:
final uri = Uri.parse('https://example.cloudfunctions.net/send_to_queue'); final bearer = 'Bearer ${await user.getIdToken()}'; final response = await http.post( uri, body: json.encode(data), headers: { // 用官方常量定义头名 HttpHeaders.authorizationHeader: bearer, HttpHeaders.contentTypeHeader: 'application/json', }, );
3. 配置Cloud Functions的CORS允许自定义头
跨域场景下,需通过CORS中间件明确允许Authorization等自定义头:
const cors = require('cors')({ origin: true, allowedHeaders: ['Authorization', 'Content-Type'] // 声明允许的头 }); exports.send_to_queue = functions.https.onRequest((req, res) => { cors(req, res, () => { // 处理请求逻辑 console.log('Authorization:', req.get('Authorization')); res.status(200).send('Success'); }); });
内容的提问来源于stack exchange,提问作者João Abrantes
相关产品推荐
相关产品推荐

