Google云功能-存储-删除图像-“ ApiError:请求期间出错”

时间:2018-11-19 16:41:57

标签: node.js firebase google-cloud-storage google-cloud-functions

更新的问题

问题是ApiError: Error during request

代码:

import * as functions from 'firebase-functions';

const cors = require('cors')({ origin: true });

import * as admin from 'firebase-admin';

const gcs = admin.storage();

export const deleteImage = functions.https.onRequest((req, res) => {

    return cors(req, res, async () => {

        res.set('Content-Type', 'application/json');
        const id = req.body.id;
        const name = req.body.name;

        const imageRef = gcs.bucket(`images/${name}`);

        if (!name || !id) {
            return res.status(400).send({message: 'Missing parameters :/'});
        }

        try {
            await imageRef.delete();
            console.log('Image deleted from Storage');
            return res.status(200).send({status: 200, message: `Thank you for id ${id}`});
        }
        catch (error) {
            console.log('error: ', error);
            return res.status(500).send({message: `Image deletion failed: ${error}`});
        }

    });
});

问题出在这里await imageRef.delete();,出现以下错误:

  

ApiError:请求期间出错。

的确,我确实在其他功能之一中加入了admin.initializeApp();,所以除非GCF有一个错误,否则这不是问题。

更多深度错误

{ ApiError: Error during request.
    at Object.parseHttpRespBody (/user_code/node_modules/firebase-admin/node_modules/@google-cloud/common/src/util.js:187:32)
    at Object.handleResp (/user_code/node_modules/firebase-admin/node_modules/@google-cloud/common/src/util.js:131:18)
    at /user_code/node_modules/firebase-admin/node_modules/@google-cloud/common/src/util.js:496:12
    at Request.onResponse [as _callback] (/user_code/node_modules/firebase-admin/node_modules/@google-cloud/common/node_modules/retry-request/index.js:198:7)
    at Request.self.callback (/user_code/node_modules/firebase-admin/node_modules/request/request.js:185:22)
    at emitTwo (events.js:106:13)
    at Request.emit (events.js:191:7)
    at Request.<anonymous> (/user_code/node_modules/firebase-admin/node_modules/request/request.js:1161:10)
    at emitOne (events.js:96:13)
    at Request.emit (events.js:188:7)
code: undefined,
errors: undefined,
response: undefined,
message: 'Error during request.' }

(已删除旧问题)

1 个答案:

答案 0 :(得分:0)

“错误:发送标头后无法设置标头”表示您尝试向客户端发送两个响应。这是无效的-您只能发送一个回复。

如果imageRef.delete()失败并触发了catch回调,您的代码显然会向客户端发送两个200类型的响应。

此外,您正在混入then / catch。它们不打算一起使用。您选择一个。通常,如果您正在使用await进行异步编程,则不要同时使用具有相同承诺的then / catch。这是带有错误处理的await的惯用用法:

try {
    await imageRef.delete()
    res.status(200).send({status: 200, message: `Thank you for id ${id}`});
} catch (error) {
    res.status(500).send({message: `Image deletion failed: ${err}`});
}

还请注意,通常会在失败时向客户端发送500响应,而不是200,这表示成功。