The issue you're encountering is due to CORS (Cross-Origin Resource Sharing) policy enforced by web browsers. CORS is a security feature implemented in web browsers to prevent web pages from making requests to a different origin (domain, protocol, or port) than the one the web page was loaded from.
When your web application running on http://localhost:8080 tries to make a request to https://us-central1-invoice-robo.cloudfunctions.net/access-control-api?action=list_companies, the browser sends a preflight request (OPTIONS request) to check if the request is allowed. The error message you're seeing indicates that the response to this preflight request does not include the necessary CORS headers, specifically Access-Control-Allow-Origin, to allow the request.
To resolve this issue, you need to configure your server (in this case, the Cloud Function access-control-api) to include the appropriate CORS headers in its responses. Here are the general steps and an example for handling CORS in a Cloud Function:
1. Handle OPTIONS Request
For the preflight request (OPTIONS method), your Cloud Function should return a response that includes the necessary CORS headers.
2. Include CORS Headers in Responses
Ensure that both the response to the preflight request and the actual request include the necessary CORS headers.
Here's an example of how you might implement this in a Node.js Cloud Function:
exports.accessControlApi = async (req, res) => {
// Set CORS headers for preflight request
if (req.method === 'OPTIONS') {
// Allows GET, POST, and OPTIONS methods
res.set('Access-Control-Allow-Methods', 'GET, POST, OPTIONS');
// Allows specific headers
res.set('Access-Control-Allow-Headers', 'Content-Type');
// Allows requests from any origin
res.set('Access-Control-Allow-Origin', '*');
// Respond to preflight request
return res.status(204).send('');
}
// Include CORS headers for actual request
res.set('Access-Control-Allow-Origin', '*');
if (req.query.action === 'list_companies') {
// Your logic to list companies
const companies = await listCompanies(); // Example function
res.json(companies);
} else {
res.status(400).send('Invalid action');
}
};
// Example function to list companies
async function listCompanies() {
// Your logic here
return [{ id: 1, name: 'Company 1' }, { id: 2, name: 'Company 2' }];
}
Key Points:
- For the preflight request (
OPTIONS method), return a 204 response with the appropriate CORS headers.
- For the actual request, include the
Access-Control-Allow-Origin header in the response.
- You can restrict
Access-Control-Allow-Origin to specific domains if you don't want to allow requests from all origins (*).
By implementing these changes in your Cloud Function, you should be able to resolve the CORS policy issue when making requests from your local development environment (http://localhost:8080) to your Cloud Function.