2017-08-03 65 views
3

我有一個應用程序,它使用YouTube API密鑰在YouTube上搜索視頻並將其顯示在我的頁面上。我剛剛瞭解到,這是揭露任何祕密給客戶端。因此,我正在考慮的解決方案是讓客戶端將請求發送到Firebase雲功能。雲功能將作爲我的API密鑰將被存儲而不是將其存儲在客戶端中的代理。如何創建通過Firebase雲端功能託管的Node.js代理服務器?

如何設置?

對於初學者,我嘗試記錄request對象,但我收到一個神祕的錯誤消息。

error: SUPERVISOR clientError { Error: Parse Error bytesParsed: 0, code: 'HPE_INVALID_METHOD' } connecting=false, _hadError=false, bytesRead=193, , fd= 
-1, reading=true, $ref=$, onread=function onread(nread, buffer) { 

這裏的GET要求由生產上述

https://localhost:5000/jpls-youtube-viewer/us-central1/helloWorld?part=snippet&type=video&q=Linkin+Park 

以下錯誤消息客戶端發送的是我的應用程序的回購:https://github.com/jpls93/jpls-youtube-viewer

而這裏的託管網站:https://jpls-youtube-viewer.firebaseapp.com/

回答

0

我通過將客戶端請求指向我的Firebase數據庫URL來解決此問題,然後我獲得了Firebase數據基URL向YouTube REST API URL請求並解析對我的客戶端的響應。我有一個與CORS有關的問題,但通過允許訪問控制源/方法可以簡單地修復這個問題

exports.helloWorld = functions.https.onRequest((request, response) => { 
    var term = request.query.q; 
    // See https://howtofirebase.com/firebase-cloud-functions-753935e80323 
    // why we're requiring it inside the function 
    var YT_URL = "https://www.googleapis.com/youtube/v3/search"; 
    const axios = require("axios"); 
    axios 
    .get(YT_URL, { 
     params: { 
     part: "snippet", 
     type: "video", 
     key: require("./secret"), 
     q: term 
     } 
    }) 
    .then(YouTubeData => { 
     response.set("Access-Control-Allow-Origin", "*"); 
     response.set("Access-Control-Allow-Methods", "GET, POST"); 
     response.status(200).send(YouTubeData.data.items); 
    }) 
    .catch(err => console.error(err)); 
}); 
+1

你是怎麼從客戶端調用這個代理函數的? – reknirt

+1

現在不能任何人使用你的代理而不是自己獲得一個youtube密鑰? – dalore

相關問題