Reputation: 3140
I cannot get my Firebase http function working when calling it from the client. Here are the errors on the client:
OPTIONS https://us-central1-my-app.cloudfunctions.net/my-func 500 ()
Failed to load https://us-central1-my-app.cloudfunctions.net/my-func:
Response to preflight request doesn't pass access control check:
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.
Here is what my function looks like:
const admin = require('firebase-admin');
const functions = require('firebase-functions');
const cors = require('cors')({origin: true});
exports.func = functions.https.onRequest((req, res) => {
return cors((req, res, () => {
res.send("hello");
}));
});
The Firebase functions log is providing this information:
TypeError: Cannot read property 'origin' of undefined
at /user_code/node_modules/cors/lib/index.js:219:39
at optionsCallback (/user_code/node_modules/cors/lib/index.js:199:9)
at corsMiddleware (/user_code/node_modules/cors/lib/index.js:204:7)
at exports.pay.functions.https.onRequest (/user_code/my-func.js:11:10)
Note that 11:10 in the call stack is this: return cors((req, res, () => {
The request I'm making is sending an object with a single key:value pair in the request body. I added the cors
middleware based on other questions I've seen on SO, but no luck!
Edit: Adding the request code:
function post(url, obj) {
return new Promise((resolve, reject) => {
const req = new XMLHttpRequest();
req.open('POST', url, true);
req.setRequestHeader("Content-type", "application/json");
req.onload = function() {
if(req.status == 200) {
return resolve(req.response);
}
else {
return reject(Error(req.statusText));
}
};
req.onerror = function() {
return reject(Error("Network Error"));
};
req.send(JSON.stringify(obj));
});
}
Upvotes: 2
Views: 2594
Reputation: 3140
Programmer error, as usual:
cors((req, res, () => {
res.send("hello");
}));
should be:
cors(req, res, () => {
res.send("hello");
});
Had an extra set of parens around the cors
args.
Upvotes: 9