Firebase“未处理的拒绝”和“设置标头后无法设置标头”JavaScript 错误

首先,请注意,我对 JS 和编码非常陌生 :)

期望的行为:我编写了以下 JS HTTPS Firebase 函数,该函数接受查询参数locationId,执行 GET API 调用并将响应保存回 Firebase。该代码根据需要正确地将数据保存到 Firebase。我遇到过类似的问题,但我正在努力使这些解决方案适应我下面的具体问题。据我所知,我只发送一次响应。

具体错误:以下是控制台输出

发送到客户端后无法设置标头

未处理的拒绝

http://img3.mukewang.com/62a15f710001b7c612280796.jpg

ITMISS
浏览 102回答 1
1回答

翻阅古今

通过展平嵌套的 Promise,您可以看到您的代码正在执行以下指令(当axios调用未引发错误时):admin.database().ref(`/venue-menus/${locationId}/`).set(response.data))  .then(response => res.status(200).send(locationId))  .catch(err => res.status(500).send({error: err})  .then(response => res.status(200).send(locationId)) // this line is always called after either of the above.  .catch(err => res.status(500).send({error: err})作为一般做法,除非需要,否则不应将 promise 与它们自己的then()和catch()处理程序嵌套,因为它会导致像这样的奇怪效果。此外,如果您的代码需要使用//end axios或//end cors消息,您应该扁平化您的代码,以便在没有这些消息的情况下有意义。将您的代码调整为“快速失败”,更正您的 API 响应并适当隐藏错误堆栈跟踪可以提供:const cors = require('cors')({  origin: true,  methods: ["GET"]});exports.doshiiGetMenuForOnboardedVenue = functions.https.onRequest((req, res) => {  cors(req, res, (err) => { // note: cors will handle OPTIONS method    if (err) {      // note: log full error at ERROR message level      console.error('Internal CORS error:', err);      // note: return only generic status message to client      return res.status(500).json({error: 'Internal Server Error'});    }    // Forbidding anything but GET requests.    if (req.method !== 'GET') {      // 405 METHOD_NOT_ALLOWED      return res.status(405)        .set('Allow', 'GET')        .json({error: 'Not Allowed!'});    }    const locationId = req.query.locationId;    console.log('locationId', locationId);    if (!locationId) {      // 400 BAD_REQUEST      return res.status(400).json({error: 'locationId missing'})    }    var token = jwttoken();    const options = {        headers: {          'content-type': 'application/json',          'authorization': 'Bearer ' + token        }      };    // note: Don't forget to enable billing for third-party APIs!    const uri = 'https://sandbox.doshii.co/partner/v3/locations/' + locationId + '/menu?lastVersion=:lastVersion&filtered=true'    axios.get(uri, options)      .then(response => admin.database().ref(`/venue-menus/${locationId}/`).set(response.data))      .then(() => {        // note: as locationId was already sent by the client, send new/useful        // information back or nothing but the right status code        res.status(200).json({ ref: `/venue-menus/${locationId}/` });      })      .catch(err => {        // note: log full error at ERROR message level        console.error('Failed to retrieve/save API data:', err);        // note: return only message to client        res.status(500).json({error: err.message || 'Internal Server Error'});      });  });});
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript