gpt4 book ai didi

javascript - Firebase 'Unhandled Rejection' 和 'Can' t 在设置 header 后设置“JavaScript 错误

转载 作者:行者123 更新时间:2023-12-02 21:16:11 25 4
gpt4 key购买 nike

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

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

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

Cannot set headers after they are sent to the client

Unhandled rejection

enter image description here

我的功能:

exports.doshiiGetMenuForOnboardedVenue = functions.https.onRequest((req, res) => {

// Forbidding PUT requests.
if (req.method === 'PUT') {
return res.status(403).send('Forbidden!');
}

cors(req, res, () => {

const locationId = req.query.locationId;

console.log('locationId', locationId);

if (locationId){

console.log('locationId', locationId);

var token = jwttoken();

const options = {
headers: {
'content-type': 'application/json',
'authorization': 'Bearer ' + token}
};

const uri = 'https://sandbox.doshii.co/partner/v3/locations/' + locationId + '/menu?lastVersion=:lastVersion&filtered=true'

axios.get(uri, options)
.then(response => {

return admin.database().ref(`/venue-menus/${locationId}/`).set(response.data)
.then(response => {
return res.status(200).send(locationId)
})
.catch(err => {
return res.status(500).send({error: err})
})

})
.then(response => {
return res.status(200).send(locationId)
})
.catch(err => {
return res.status(500).send({error: err})
})//end axios

} else {

return res.status(500).send({error: 'locationId missing'})

}//end if-else (!locationId)

})//end cors

});

最佳答案

通过展平嵌套的 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'});
});
});
});

关于javascript - Firebase 'Unhandled Rejection' 和 'Can' t 在设置 header 后设置“JavaScript 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60962980/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com