如何解决Firebase功能环境中的CORS? [英] How to solve CORS in firebase functions enviroment?
问题描述
我遇到了CORS
问题.在我的functions/index.js
中,我有:
I´m runnig into CORS
issues. In my functions/index.js
I have:
const cors = require('cors')({
origin: true
});
我的端点是https://sis-t.redsys.es:25443/sis/realizarPago
.我需要使用来自客户端的适当参数对此URL进行POST
,这是在Firebase环境之外.我也有允许外部网络的正确计划,但是向不同于原始地址的地址发出请求会触发CORS
问题:
My endpoint is https://sis-t.redsys.es:25443/sis/realizarPago
. I need to do a POST
to this url with apropiate parameters from the client, and this is outside firebase enviroment. I also have the correct plan to allow external network, but making a request to a different address than the origin one, triggers a CORS
problem:
- error log
- network log
我读到您只需要修改标题,但这仅在您向自己的服务器发出请求时才适用.当您执行http.onRequest()
时,可以在函数内部使用中间件,但是在对外部服务器进行POST时会发生什么?
I have read that you only need to modify the headers, but that only applies if you are making a request to your own server. When you do the http.onRequest()
, you can use a middleware inside the function, but what happens when you make a POST to an external server?
这是执行POST
的axios
函数:
cardPay: function () {
this.cardProcess = true
axios({
method: 'post',
url: 'https://us-central1-cutre-windrider.cloudfunctions.net/cardPay',
data: {
verifiedUserLogged: this.userLogged.uid,
cart: this.cartItemList,
finalPrice: this.serverPrice,
deliveryInfo: this.userLogged.deliveryAdress,
name: this.userLogged.displayName || false,
email: this.userLogged.email
}
})
.then(response => {
this.requestData = response
this.redsysRedirect(response.data.data)
})
.catch(console.log)
},
redsysRedirect: function (data) {
axios.post('https://sis-t.redsys.es:25443/sis/realizarPago', {
'Ds_SignatureVersion': 'HMAC_SHA256_V1',
'Ds_MerchantParameters': data.merchantParameters,
'Ds_Signature': data.signature
}).then(console.log).catch(console.log)
这些是服务器端功能:
exports.cardPay = functions.https.onRequest((req, res) => {
return cors(req, res, () => {
const cart = req.body.cart
const user = req.body.verifiedUserLogged
const key = admin.database().ref(`sales/${user}`).push().key
processCart(cart).then(result => {
console.info(createPayment(result, key))
return res.json({ "data": createPayment(result, key) }).end()
}).catch(console.log)
})
})
function processCart(cart) {
return new Promise((resolve, reject) => {
Promise.all(cart.map(i => switcher(i)))
.then(prices => resolve(
prices.reduce(
(finalPrice, price) => price + finalPrice, 0)
)).catch(console.log)
});
}
function switcher(item) {
switch (item.destiny) {
case 'bookedLessons':
return lessonPrice(item.name, item.index)
case 'bookedRentals':
return rentalPrice(item.id, item.index, item.insurancePurchased, item.insuranceId)
case 'bookedLodgins':
return item.reservationData ? roomPriceWithReservation(item.id, item.quantity, item.persons, item.reservationData) : roomPriceNoReservation(item.id, item.quantity, item.persons)
case 'deliveries':
return productPrice(item.id, item.quantity)
case 'bookedCar':
return carPrice(item.id, item.index)
case 'bookedStorage':
return storagePrice(item.index)
case 'bookedTransportation':
return transportationPrice(item.id, item.index, item.persons, item.roundTrip)
case 'bookedDoublePack':
return doublePack(item.id, item.persons)
case 'bookedTriplePack':
return triplePack(item.id, item.persons)
default:
break
}
}
function createPayment(total, orderId) {
let redsys = new Redsys();
let mParams = {
"DS_MERCHANT_AMOUNT":total.toString(),
"DS_MERCHANT_ORDER":orderId,
"DS_MERCHANT_MERCHANTCODE": "025988262",
// "DS_MERCHANT_MERCHANTCODE":tpvInfo.fucCode,
"DS_MERCHANT_CURRENCY":"978",
// "DS_MERCHANT_CURRENCY":tpvInfo.currency,
"DS_MERCHANT_TRANSACTIONTYPE":"0",
// "DS_MERCHANT_TRANSACTIONTYPE":tpvInfo.transaction_type,
"DS_MERCHANT_TERMINAL": "001",
// "DS_MERCHANT_TERMINAL":tpvInfo.terminal,
"DS_MERCHANT_MERCHANTURL":'http://localhost:8080',
"DS_MERCHANT_URLOK":'http://localhost:8080/home?foo=true',
"DS_MERCHANT_URLKO":'http://localhost:8080/home?foo=false'
};
return {signature: redsys.createMerchantSignature(/* tpvInfo.secret */ "sq7HjrUOBfKmC576ILgskD5srU870gJ7", mParams) , merchantParameters: redsys.createMerchantParameters(mParams), raw: mParams};
}
推荐答案
对于将来会遇到此问题(或我未来的自己)的人:
For someone who will meet this issue in the future (or my future self):
如果您已经使用cors
程序包配置了CORS,并且认为您已正确配置它,并且在浏览器控制台中仍然出现CORS错误,请查看本文:
If you've already configured CORS using cors
package, and you think you configured it correctly, and still have CORS error in the browser console, check this article:
https://haha.world/firebase-cors/
基本上,这是一个误导性的错误,是从Google Cloud Functions返回的,而实际上该错误在您的代码逻辑内部(完全与CORS完全无关)
Basically, it's a misleading error returns from Google Cloud Functions, when actually the error is inside your code logic (which is totally not related to CORS at all)
因此,修复此错误的第一步是检查Google Cloud Functions日志(或Firebase Cloud Functions日志),以查看您的函数是否由于代码中的任何错误而崩溃.然后修复它.
So the first step to fix this bug is to check Google Cloud Functions logs (or Firebase Cloud Functions logs) to see if your function crashed because of any error in your code. Then fix it.
注意 :对于没有我上面描述的问题的人,您可以查看其他答案或查看以下资源:
Note: For someone that doesn't have the issue that I described above, you can see other answers, or check these resources:
- https://expressjs.com/en/resources/middleware/cors.html
- https://firebase.google.com/docs/functions/http- events#using_existing_express_apps
- https://expressjs.com/en/resources/middleware/cors.html
- https://firebase.google.com/docs/functions/http-events#using_existing_express_apps
这篇关于如何解决Firebase功能环境中的CORS?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!