【发布时间】:2019-04-08 04:12:38
【问题描述】:
我正在尝试使用 Firebase 云功能向 3rd 方 API (Yelp) 发出 axios get 请求。从我目前阅读的相关问题来看,其他开发人员遇到了类似的问题,主要是因为他们在 spark 计划中,或者没有启用 cors。我自己目前正在Blaze计划中。
以下是问题的细分:
-使用: React/Redux
-步骤:
1-我在我的操作文件 (/actions/index) 中编写了一个函数,该函数对 firebase 云函数进行 axios 调用
/*actions/index.js*/
import { dbConfig } from "../config/firebase";
import { LOGIN, LOAD_USERS, LOAD_ACTIVITIES, SEARCH_VENUE, RETRIEVEMATCH, SAVE_VENUE } from "./types";
import axios from "axios";
export const searchActivities = (search) => async(dispatch) => {
/*call to cloud function*/
axios.get("https://us-central1-we-party-210101.cloudfunctions.net/searchActivities", {headers:{ Authorization: `Bearer ${dbConfig.apiKey}`}})
.then(res => {
console.log(" search venue res: ", res.data);
dispatch({
type: SEARCH_VENUE,
payload: res.data
})
})
.catch( e => {
console.log("searchActivities error: ", e);
})
}
2-在云函数(/functions/index)中,我启用 cors ,将我的 Yelp api 令牌添加为授权标头并发出 get 请求。
/*/functions/index.js*/
const functions = require('firebase-functions');
const cors = require('cors')({origin: true});
var axios = require('axios');
var tokens = require('./functionSecrets');
// this function works fine when called the exact same way as the one below
exports.helloWorld = functions.https.onRequest((request, response) => {
console.log("Hello World");
});
exports.searchActivities = functions.https.onRequest( (request, response) => {
// enable cors
cors(request, response, () => {
// request to yelp api
axios.get("https://api.yelp.com/v3/businesses/search", {headers:{ Authorization: `bearer ${tokens.yelpKey}`}})
.then(r => {
console.log("Cloud yelp resp", r);
})
.catch( e => {
console.log( "Cloud yelp error: ", e);
})
})
})
-期望的行为:
Yelp api 响应正文已记录在我的开发工具控制台中。 注意:此时我并不担心动作文件中的调度,因为我什至一开始都没有收到响应。
-实际行为:
运行6s后请求超时。 注意: 在我的本地服务器上,相同的请求大约需要 0.8 秒。 以下是我的 Firebase 函数中的日志:
搜索活动 函数执行耗时 60003 毫秒,完成状态为:'timeout'
总的来说,我对开发还很陌生,我看不出我在这里缺少什么。我相信这是一件小事,希望有人能指出我正确的方向。
提前感谢您的帮助!
P.S:我确保解决了类似的问题,但如果这仍然是重复的,我提前道歉。
【问题讨论】:
标签: javascript reactjs firebase redux google-cloud-functions