部署后NodeJS Firebase功能失败

时间:2020-02-07 02:28:04

标签: node.js firebase express cors google-cloud-functions

我有一个NodeJS并使用Firebase函数。在本地主机上运行时,它将发送预期的JSON。将其部署到Firebase后,尝试击中端点时出现以下错误:

TypeError: Cannot read property 'stack' of undefined
    at getErrorDetails (/worker/worker.js:365:14)
    at logAndSendError (/worker/worker.js:579:12)
    at process.<anonymous> (/worker/worker.js:854:5)
    at emitTwo (events.js:126:13)
    at process.emit (events.js:214:7)
    at emitPendingUnhandledRejections (internal/process/promises.js:108:22)
    at process._tickDomainCallback (internal/process/next_tick.js:230:7)

前端返回以下错误:

Access to XMLHttpRequest at 'https://vear-node.firebaseapp.com/xmlfeed' from origin 'http://localhost:3000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

我怀疑这是一个CORS问题,因为我使用的是Express cors中间件,并且没有问题地访问了该服务器上的其他端点。

代码:

const app = express().use(cors());

app.get('/xmlfeed', cors(), async (request, response) => {
    const feedResponse = await getXMLFeedData();
    const json = { products: feedResponse };
    response.json(json);
});
export const getXMLFeedData = async (): Promise<any> => {
    try {
        const response = await axios.get('https://www.nae-vegan.com/extend/catalog_81.xml');

        const parsedResponse = await parseXMLResult(response);
        const jsonString = JSON.stringify(parsedResponse);
        const jsonObject = JSON.parse(jsonString);
        const formatted = await formatNAEProducts(jsonObject);

        return Promise.resolve(formatted);
    } catch (error) {
        return Promise.reject(error);
    }
};
const parseXMLResult = async (response: any): Promise<any> => {
    var parsedResult: any = undefined;

    try {
        await parser.parseString(response.data, (err, result) => {
            parsedResult = result;
        });

        return Promise.resolve(parsedResult);
    } catch (error) {
        return Promise.reject(error);
    }
};

端点:https://vear-node.firebaseapp.com/xmlfeed

有没有人知道在本地部署完全正常后,会导致错误发生的原因?

谢谢!

1 个答案:

答案 0 :(得分:-1)

您必须允许所有cors原点请求进入标头。由于您使用的是Express框架,因此必须将其包含在app.use方法中。检查下面的代码。

app.use((req, res) => {
  res.header("Access-Control-Allow-Origin", "*");
  res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
});