我正在嘗試在使用某些文本并需要 api 密鑰的網站上首次用戶登錄時使用 Axios POST 進行 api 呼叫。我做了類似const functions = require('firebase-functions')和var axios = require('axios')上面的基本初始化作業。
exports.addSummaryMessage = functi ons.auth.user().onCreate(async (user) => {
const response = await axios.post(
'https://example.com/stuff',
{
headers: {
contentType: 'content/json',
Authorization:
'Bearer APIKEY',
},
text: 'wooooww',
}
)
await admin.firestore().collection('messages').add({
name: 'Firebase Bot',
profilePicUrl: '/images/firebase-logo.png', // Firebase logo
text: JSON.stringify(response),
timestamp: admin.firestore.FieldValue.serverTimestamp(),
})
})
在我的函式日志中,我收到類似 >addSummaryMessage 函式執行耗時 231 毫秒的訊息。完成狀態:錯誤
我可以跟蹤從 api 收到的呼叫,它從不注冊或發回輸出。request, response我認為我無法使用 functions.auth.user().onCreate() 獲得的所有 CORS這里出了什么問題?我的 API 在 reqbin 中使用這個 raw
POST /stuff
Authorization: Bearer APIKEY
Host: example.com
Accept: application/json
Content-Type: application/json
Content-Length: 30
{
"text":"wooooww"
}
編輯:讓它在函式中使用此文本:
var data = {}
var url =
'https://example.com'
var resp
await axios
.post(url, data, {
headers: {
contentType: 'content/json',
Authorization:
'Bearer API Key',
},
})
.then((res) => {
resp = res.data.stuff
admin.firestore().collection('messages').add({
name: 'Firebase Bot',
profilePicUrl: '/images/firebase-logo.png', // Firebase logo
text: resp,
timestamp: admin.firestore.FieldValue.serverTimestamp(),
})
})
.catch((err) => {
console.log(err)
})
編輯 2
我的 api 不需要文本來運行,我很困惑如何通過data這對我來說將文本傳遞到帖子中
var userText = 'wow'
var data = {}
data['text'] = userText
var url = ....
uj5u.com熱心網友回復:
如果沒有更多詳細資訊,很難確定您遇到的問題。但是您提到第二個代碼有效。
此外,我們可以看到您沒有正確管理 Cloud Function 的生命周期:您沒有回傳 Promise。這通常會導致一些不穩定的行為:云功能有時有效,有時無效......
所以以下應該可以作業(當然未經測驗,因為我們不知道通過 Axios 呼叫的 API):
const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp(); // <= This is important
exports.addSummaryMessage = functions.auth.user().onCreate(async (user) => {
const response = await axios.post(
'https://example.com/stuff',
{
headers: {
contentType: 'content/json',
Authorization:
'Bearer APIKEY',
},
text: 'wooooww',
}
)
await admin.firestore().collection('messages').add({
name: 'Firebase Bot',
profilePicUrl: '/images/firebase-logo.png', // Firebase logo
text: JSON.stringify(response),
timestamp: admin.firestore.FieldValue.serverTimestamp(),
})
return null; // <= This is important
})
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/464942.html
