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();
// CORS 설정
const corsOptions = {
origin: 'https://nulligpt.web.app',
methods: ['GET', 'POST', 'OPTIONS'],
allowedHeaders: ['Content-Type'],
credentials: true,
};
// CORS 미들웨어 사용
app.use(cors(corsOptions));
app.use(bodyParser.json());
// OpenAI API 키
const OPENAI_API_KEY = 'sk-';
const client = new OpenAI({
apiKey: OPENAI_API_KEY,
});
// CORS preflight 요청에 대한 핸들링
app.options('*', cors(corsOptions));
// 이름 번역 API 엔드포인트
app.post('/api', async (req, res) => {
const { name } = req.body;
if (!name) {
console.log('Name is missing in the request.');
return res.status(400).json({ error: 'Name is required' });
}
try {
const response = await client.chat.completions.create({
model: 'gpt-3.5-turbo',
messages: [{ role: 'user', content: `Translate this name to Korean: ${name}` }],
});
if (response.choices && response.choices.length > 0) {
const translatedName = response.choices[0].message.content;
console.log('Successfully received response from OpenAI:', translatedName);
return res.json({ translatedName });
} else {
return res.status(500).json({ error });
}
} catch (error) {
console.log( error);
}
});
exports.api = functions.https.onRequest((req, res) => {
cors(req, res, async () => {
if (req.method === 'OPTIONS') {
return res.sendStatus(200);
} else {
try {
await app(req, res);
} catch (err) {
console.log( err);
}
}
});
});
<!DOCTYPE html>
<html lang="ko">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link href="nulli.css" rel="stylesheet" type="text/css"/>
</head>
<body>
<div class="allcon">
<div class="toplogo"></div>
<form id="nameForm" class="form">
<input class="input" type="text" id="nameInput" placeholder="Enter your name" required>
<button type="submit">Translate</button>
</form>
<div class="word">
<p class="firstword">Enter your name</p>
<p class="firstword">you can get korean name</p>
</div>
<div id="translated-name" class="output"></div>
</div>
<script>
document.getElementById('nameForm').addEventListener('submit', async function(event) {
event.preventDefault();
const name = document.getElementById('nameInput').value;
try {
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 }),
});
if (response.ok) {
const data = await response.json();
document.getElementById('translated-name').innerText = `${data.translatedName}`;
} else {
document.getElementById('translated-name').innerText = 'Error: Failed to translate name';
}
} catch (error) {
console.error('Error:', error);
document.getElementById('translated-name').innerText = 'Error: Failed to fetch the translation';
}
});
</script>
</body>
</html>
I created a feature that translates the text I input into Korean.
It worked well during local testing, so I deployed it using
Firebase Hosting and created a function. My Firebase project name is ‘nulligpt’
so the URL is https://nulligpt.web.app/ When sending POST requests from the client,
I use https://us-central1-nulligpt.cloudfunctions.net/api (where ‘api’ is the Firebase function name).
Initially, a CORS error appeared, which seemed correctly resolved, but now, no matter how many times I send a POST request, I receive either a 404 or 500 error.
Below is the network request log.
Request URL:
https://us-central1-nulligpt.cloudfunctions.net/api
Request Method:
OPTIONS
Status Code:
408 Request Timeout
Remote Address:
216.239.36.54:443
Referrer Policy:
strict-origin-when-cross-origin
:authority:
us-central1-nulligpt.cloudfunctions.net
:method:
OPTIONS
:path:
/api
:scheme:
https
accept:
/
accept-encoding:
gzip, deflate, br, zstd
accept-language:
ko-KR,ko;q=0.9,en-US;q=0.8,en;q=0.7
access-control-request-headers:
content-type
access-control-request-method:
POST
origin:
https://nulligpt.web.app
priority:
u=1, i
referer:
https://nulligpt.web.app/
sec-fetch-dest:
empty
sec-fetch-mode:
cors
sec-fetch-site:
cross-site
user-agent:
Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/129.0.0.0 Safari/537.36