I deployed the frontend with Firebase Hosting, and my project name is ‘nulligpt.’ In the function, it says to make requests to the endpoint https://us-central1-nulligpt.cloudfunctions.net/api. However, I encounter a CORS error when making the requests. It worked fine when running locally, so I don’t understand what’s happening.
Access to fetch at 'https://us-central1-nulligpt.cloudfunctions.net/api' from origin 'https://nulligpt.web.app' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.Understand this error
const functions = require('firebase-functions');
const express = require('express');
const bodyParser = require('body-parser');
const cors = require('cors');
const OpenAI = require('openai');
const app = express();
app.use(cors({ origin: true }));
app.use(bodyParser.json());
const OPENAI_API_KEY = 'sk-';
const client = new OpenAI({
apiKey: OPENAI_API_KEY,
});
app.post('/api', async (req, res) => {
const { name } = req.body;
if (!name) {
console.error('Name is missing from request body');
return res.status(400).json({ error: 'Name is required' });
}
try {
console.log(`Request received with name: ${name}`);
const response = await client.chat.completions.create({
model: 'gpt-3.5-turbo',
messages: [{ role: 'user', content: `Translate this name to Korean: ${name}` }],
});
console.log('OpenAI API response:', response);
const translatedName = response.choices[0].message.content.trim();
console.log(`Translated name: ${translatedName}`);
return res.json({ translatedName });
} catch (error) {
console.error('Error communicating with OpenAI:', error.response?.data || error.message || error);
return res.status(500).json({ error: 'Failed to translate name' });
}
});
exports.api = functions.https.onRequest(app);
const response = await fetch('https://us-central1-nulligpt.cloudfunctions.net/api', {
method: 'POST',
headers: {
'Content-Type': 'application/json; charset=utf-8',
},
body: JSON.stringify({ name: name }),