【发布时间】:2022-01-10 17:45:56
【问题描述】:
我在尝试使用带有我的 react 应用程序的 firebase 云函数模拟器在本地调用我的可调用函数时收到以下 CORS 错误:
Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at https://us-central1-xxxx-xxxxx.cloudfunctions.net/getSignedUrls. (Reason: CORS header ‘Access-Control-Allow-Origin’ missing). Status code: 302.
这是我的云功能:
/functions/index.js
const functions = require('firebase-functions')
const AWS = require('aws-sdk')
const fs = require('fs')
const path = require('path')
const admin = require('firebase-admin')
admin.initializeApp()
exports.getSignedUrls = functions.https.onCall((data, context) => {
const cloudfrontAccessKeyId = "XXXXXXXXX"
let cloudfrontPrivateKey = fs.readFileSync(path.join(__dirname, 'private_key.pem'))
const signer = new AWS.CloudFront.Signer(cloudfrontAccessKeyId, cloudfrontPrivateKey)
const distName = "xxxxxxxxx.cloudfront.net"
const s3Path = data.path
let cfObjectUrl = 'https://' + distName + '/' + s3Path
const twoDays = 2*24*60*60*1000
const signedUrl = signer.getSignedUrl({
url: cfObjectUrl,
expires: Math.floor((Date.now() + twoDays)/1000)
})
return {url: signedUrl}
})
这里是我创建对我的应用程序云功能的引用:
/src/firebase.js
import firebase from 'firebase/compat/app'
import { getAuth } from "firebase/auth";
import { getDatabase } from "firebase/database"
import {getFunctions} from 'firebase/functions'
const app = firebase.initializeApp({
apiKey: "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx",
authDomain: "xxxx-xxxx.firebaseapp.com",
databaseURL: "https://xxx-xxxx-default-rtdb.firebaseio.com",
projectId: "xxxx-xxxx",
storageBucket: "xxxx-xxxx.appspot.com",
messagingSenderId: "xxxxxxxxxxx",
appId: "1:938967916081:web:xxxxxxxxxxxxxxxxxxx",
measurementId: "G-xxxxxxxx"
})
export const auth = getAuth(app)
export const db = getDatabase(app)
export const functions = getFunctions(app)
export default app
这是我尝试调用云函数的组件:
/src/components/SignedUrlTest.js
import React, { Component } from 'react';
import {httpsCallable} from 'firebase/functions'
import {functions} from '../firebase'
class SignedUrlTest extends Component {
constructor(props){
super(props)
this.state = { url: null}
this.getUrl = this.getUrl.bind(this)
}
getUrl(){
var getSignedUrls = httpsCallable(functions, 'getSignedUrls');
getSignedUrls({path: "Melissa-OShaughnessy-6-1024x683.jpg"
}).then((result) => { console.log(result.data) })
.catch((error) => {
console.log(error)
})
}
render() {
return (
<div>
<button onClick={this.getUrl}>geturl</button>
</div>
);
}
}
export default SignedUrlTest;
我已经阅读了文档 (https://firebase.google.com/docs/functions/callable),但似乎无法弄清楚为什么我无法使用客户端 SDK 调用我的函数。我已经在同一环境中测试了本地模拟的“onRequest”云函数,并且能够使用我的网络浏览器获得适当的响应,但我无法弄清楚如何从我的应用程序调用“onCall”函数。 任何帮助将不胜感激:)
【问题讨论】:
-
根据错误,您的代码中缺少
CORS标头。跨域资源共享,是一种浏览器机制,允许在源 A 运行的站点从源 B 请求资源。检查此thread,这可能非常有用。
标签: javascript node.js reactjs firebase google-cloud-functions