尝试通过http get获取Firebase数据时出现错误

问题描述 投票:0回答:1

我正在尝试通过HTTP get请求获取我的Firestore数据,但尝试时会收到此错误。我认为,如果我在firestore中的数据为JSON格式会更容易。我不知道是否可以设置。

<!DOCTYPE html>
<html lang="en">

 <head>
<meta charset="utf-8">
<title>Error</title>
</head>

<body>
<pre>Cannot GET /api/v1/getsensor/0/led1</pre>
</body>

</html>

这是我的Firestore获取代码:

import * as functions from 'firebase-functions';
import * as admin from 'firebase-admin';
import * as firebaseHelper from 'firebase-functions-helper/dist';
import * as express from 'express';
import * as bodyParser from 'body-parser';

admin.initializeApp(functions.config().firebase);
const db = admin.firestore();
db.settings({timestampInSnapshots: true});

const app = express();
const main = express();

main.use(bodyParser.json());
main.use(bodyParser.urlencoded({extended: false}));
main.use('/api/v1', app);

const sensorCollection = 'dadosusuarios';
export const webApi = functions.https.onRequest(main);

app.patch('/sensor/:sensorId', async(req, res) => {
try{
    await firebaseHelper.firestore.updateDocument(db, sensorCollection, req.params.sensorId, 
req.body);
    res.status(200).send("Update Success");
}catch (error){
    res.status(204).send("Patch Error");
}
});

app.get('/getsensor', async(req, res) =>{
try{
    await firebaseHelper.firestore.getDocument(db, sensorCollection, req.params.sensorId).then(doc => 
console.log('data'));
    res.status(200).send("Get Success");
}catch (error){
    res.status(204).send("Get Error");
}
});

这是我尝试访问数据的方式,我使用邮递员进行了测试:

https://home-automation-6ed64.web.app/api/v1/getsensor/mydocid/led1

这是我的消防站的图像:enter image description here

typescript http google-cloud-firestore get google-cloud-functions
1个回答
0
投票

您使用Firestore API检索值的最佳简便方法。这样,您将可以根据需要轻松访问数据并以JSON格式返回值。

为了实现这一点,您需要遵循一种URL模式来检索值。以下网址是一个示例:

https://firestore.googleapis.com/v1/projects/YOUR_PROJECT_ID/databases/(default)/documents/dadosusuarios/<usuario>

您可以在这里的官方文档中找到更多信息:Making Rest Calls

但是,如果需要使用正在使用的Express方法,可以查看此文档以获取更多信息:Call functions via HTTP requests

而且我首先将以下内容添加到您的代码中,因此身份验证和CORS问题不会影响您。

// Automatically allow cross-origin requests
app.use(cors({ origin: true }));

// Add middleware to authenticate requests
app.use(myMiddleware);

让我知道信息是否对您有帮助!

© www.soinside.com 2019 - 2024. All rights reserved.