我需要与cors合作的firebase功能出现问题。根据文档和我读过的所有帖子,它应该正常工作,但似乎无论我尝试什么,我都会遇到同样的错误:
Failed to load <URL>: No 'Access-Control-Allow-Origin' header is present on the requested resource.
Origin 'http://localhost:3000' is therefore not allowed access. The response had HTTP status code 500.
If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.
这是我的firebase函数index.js文件中的相应代码:
const functions = require('firebase-functions');
const admin = require('firebase-admin');
const cors = require('cors')({origin: true});
const stripe = require('stripe')('<TEST_KEY>');
const gcs = require('@google-cloud/storage')({keyFilename: '<PATH_TO_KEY>'});
const Easypost = require('@easypost/api');
const api = new Easypost('<TEST_KEY>');
admin.initializeApp(functions.config().firebase);
exports.processOrder = functions.https.onRequest((req, res) => {
cors(req, res, () => {
var body = JSON.parse(req.body);
if (
!body.shipment_id ||
!body.items ||
!body.card
) return res.set('Access-Control-Allow-Origin', '*').send({error: true, message: 'Missing information'});
getPrices(body.items, (err, prices, totalPrice) => {
if (err) return res.set('Access-Control-Allow-Origin', '*').send({error: err, message: "Error"})
// Create a new customer and then a new charge for that customer:
stripe.customers.create({
email: 'test@example.com'
}).then((customer) => {
return stripe.customers.createSource(customer.id, {
source: body.card.token.id
});
}).then((source) => {
return stripe.charges.create({
amount: (totalPrice * 100),
currency: 'usd',
customer: source.customer
});
}).then((charge) => {
return res.set('Access-Control-Allow-Origin', '*').send({error: false, message: "Success"});
}).catch((err) => {
console.log(err);
return res.set('Access-Control-Allow-Origin', '*').send({error: err, message: "Error"});
});
});
});
});
非常感谢任何帮助:)
编辑:只是想注意:我只尝试设置res.set('Access-Control-Allow-Origin', '*')
而不使用cors中间件,我尝试不设置标头并仅使用cors。两者都不奏效:(
解决方案:正如@sideshowbarker在评论中所说,我的功能在返回之前在别处发生了错误。 Access-Control-Allow-Origin从未被设置过。一旦我修正了错误,那一切都很好! TY!
答案 0 :(得分:0)
在节点中,您可以使用包来解决此问题。要启用所有CORS,请安装以下软件包:
npm install cors
然后假设您正在使用express
,则可以通过以下代码行启用CORS:
var cors = require('cors');
app.use(cors());