【问题标题】:Firebase response: undefined is not an objectFirebase 响应:未定义不是对象
【发布时间】:2019-03-21 02:07:47
【问题描述】:

我正在尝试将数据保存到 Firebase 存储中。
一般来说,我的方法和功能有效,在 FireBase 日志中我得到:

  • 函数执行耗时 1442 毫秒,完成状态码:201

  • alert15

  • alert14: null||[object Object]

  • alert12:

  • alert11:

  • 未配置计费帐户。外部网络无法访问,配额受到严格限制。配置结算帐号以删除 这些限制

  • 函数执行开始

我的功能:

const functions = require('firebase-functions');
const cors = require("cors")({origin: true});
const fs = require("fs");
const UUID = require("uuid-v4");

const gcconfig = {
    projectId: "myrojectid",
    keyFilename: "mykeyfile.json"
};

const gcs = require("@google-cloud/storage")(gcconfig);

// // Create and Deploy Your First Cloud Functions
// // https://firebase.google.com/docs/functions/write-firebase-functions
//
exports.storeImage = functions.https.onRequest((request, response) => {
    console.log("alert11: ")
    cors(request, response, () => {
        console.log("alert12: ")
        const body = JSON.parse(request.body);
        fs.writeFileSync("/tmp/uploaded-image.jpg", body.image, "base64", err => {
            console.log(err => console.log("alert13: " + err));
            return response.status(500).json({error: err})
        });
        const bucket = gcs.bucket("myapp.appspot.com");
        const uuid = UUID();
        bucket.upload(
            "/tmp/uploaded-image.jpg",
            {
                uploadType: "media",
                destination: "/places2/" + uuid + ".jpg",
                metadata: {
                    metadata: {
                        contentType: "image/jpeg",
                        firebaseStorageDownloadTokens: uuid
                    }
                }
            }, (err, file) => {
                console.log("alert14: " + err + "||" + file)
                if (!err) {
                    console.log("alert15");
                    response.status(201).json({
                        imageUrl:
                            "https://firebasestorage.googleapis.com/v0/b/" +
                            bucket.name +
                            "/o/" +
                            encodeURIComponent(file.name) +
                            "?alt=media&token=" +
                            uuid
                    })
                } else {
                    console.log("alert16: ")
                    console.log(err);
                    response.status(500).json({error: err})
                }
            });
    });
});

我的方法:

import {ADD_PLACE, DELETE_PLACE} from './actionTypes';

export const addPlace = (placeName, location, image) => {
    return dispatch => {
        fetch("https://us-central1-myapp.cloudfunctions.net/storeImage", {
            method: "POST",
            body: JSON.stringify({
                image: image.base64
            })
        })
            .catch(err=> console.log(err))
            .then(res => {res.json(); console.log("alert2 " + {res})})
            .then(parsedRes => {
                console.log("alert1: " + parsedRes);
                const placeData = {
                    name: placeName,
                    location: location,
                    image: parsedRes.imageUrl
                };
                return  fetch("https://myapp.firebaseio.com/places.json", {
                    method: "POST",
                    body: JSON.stringify(placeData)
                }).catch(err => console.log("alert13: " + err))
            })
            .catch(err => console.log("alert4", err))
            .then(res => res.json())
            .catch(err => console.log("alert5: " + err))
            .then(parsedRes => {
                console.log("alert6", parsedRes);
            }).catch(err => console.log("alert17: " + err));
    };
};

export const deletePlace = (key) => {
    return {
        type: DELETE_PLACE,
        placeKey: key
    };
};

但在我的 IDE 的本地控制台中,我得到了这个:

  • alert1:未定义
  • 'alert4', { [TypeError: undefined is not an object (evalating 'parsedRes.imageUrl')]

我为此浪费了 3 天时间,但进度仍为 0。
这里有什么问题?如何解决?

【问题讨论】:

  • 你对 parsedRes 有什么期待?由于它没有得到任何东西,这就是为什么您在 alert1 和 alert4 中未定义的原因。它只是显示得很好。
  • 我除了来自 firebase 的 imageUrl
  • 嗯,那是你的 API 的问题,你应该在 Angular 中使用之前对其进行测试。你可以试试 Postman 来测试你的 API。
  • 它的 Firebase,不是我自己的 api
  • 是的,但是无论您对图像或测试的期望是什么,您都可以在 Angular 中使用之前对其进行测试

标签: javascript firebase google-cloud-functions firebase-storage


【解决方案1】:

您没有正确使用 Promise 链接。您需要将then() 回调的结果显式返回给链中的下一个处理程序。如果不返回任何内容,下一个 then() 回调将变得未定义。例如:

        .then(res => {res.json(); console.log("alert2 " + {res})})

在这行代码中,您不会返回任何内容以传递给链中的下一个处理程序。

事实上,上面的then() 回调是不必要的,因为它不会启动任何其他异步工作。您可以在随后的then() 块中调用res.json(),就在第二次获取之前。由于之前的异步工作,您通常只有在您有更多异步工作要做时才添加另一个 then() 块。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-11-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多