Sign In

개발 코드

index.js :
import OpenAI from 'openai';
import dotenv from 'dotenv';
import express from 'express';
import bodyParser from 'body-parser';
import cors from 'cors'; // CORS 모듈 가져오기
// 환경 변수 로드
dotenv.config();
// OpenAI 클라이언트 설정
const openai = new OpenAI({
apiKey: process.env.OPENAI_API_KEY,
});
// OpenAI API 요청 함수
async function getChatCompletion(userMessage) {
try {
const completion = await openai.chat.completions.create({
model: "gpt-3.5-turbo",
messages: [
{ role: "system", content: "당신은 ALLTHE라는 정보 검색 서비스의 조력자입니다. ALLTHE는 각종 플랫폼, 노마드, 사이트 정보를 담고 있습니다." },
{ role: "user", content: userMessage } // 사용자의 메시지를 추가
]
});
    const hallo = completion.choices[0].message.content; // 응답을 hallo 변수에 저장
    console.log(hallo); // 응답을 콘솔에 출력
    return hallo; // hallo 값을 반환
} catch (error) {
    console.error("Error with OpenAI API:", error.response ? error.response.data : error.message);
    throw new Error('Failed to get response from OpenAI API');
}
}
// Express 서버 설정 및 실행 함수
function startServer() {
const app = express();
app.use(cors()); // CORS 설정 추가
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));

// 기본 경로 처리 (서버 상태 확인용)
app.get('/', (req, res) => {
    res.send('Server is running!');
});

// POST 요청에 대한 처리
app.post('/hallo', async (req, res) => {
    const userMessage = req.body.message; // 프론트엔드에서 보낸 메시지 가져오기
    try {
        const hallo = await getChatCompletion(userMessage); // ChatGPT 응답을 받아 hallo에 저장
        res.json({ response: hallo }); // hallo 값을 JSON 형식으로 프론트엔드에 전달
    } catch (error) {
        res.status(500).json({ error: 'Error occurred while fetching the response.' });
    }
});

const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
    console.log(`Server is running on http://localhost:${PORT}`); // 서버 실행 확인 메시지
});
}
// 서버 시작
startServer();
import OpenAI from 'openai';
import dotenv from 'dotenv';
import express from 'express';
import bodyParser from 'body-parser';
import cors from 'cors'; // CORS 모듈 가져오기
import path from 'path';
import { fileURLToPath } from 'url';
// __dirname 설정 (ES 모듈 환경용)
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
// 환경 변수 로드
dotenv.config();
const app = express();
// OpenAI 클라이언트 설정
const openai = new OpenAI({
apiKey: process.env.OPENAI_API_KEY,
});
// OpenAI API 요청 함수
async function getChatCompletion(userMessage) {
try {
const completion = await openai.chat.completions.create({
model: "gpt-3.5-turbo",
messages: [
{ role: "system", content: "당신은 ALLTHE라는 정보 검색 서비스의 조력자입니다. ALLTHE는 각종 플랫폼, 노마드, 사이트 정보를 담고 있습니다." },
{ role: "user", content: userMessage } // 사용자의 메시지를 추가
]
});
    const hallo = completion.choices[0].message.content; // 응답을 hallo 변수에 저장
    console.log(hallo); // 응답을 콘솔에 출력
    return hallo; // hallo 값을 반환
} catch (error) {
    console.error("Error with OpenAI API:", error.response ? error.response.data : error.message);
    throw new Error('Failed to get response from OpenAI API');
}
}
// Express 서버 설정 및 실행 함수
function startServer() {
app.use(cors()); // CORS 설정 추가
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
// 정적 파일 경로 설정
const frontendPath = path.join(__dirname, '../frontend');
app.use(express.static(frontendPath));

// 기본 경로에서 index.html 제공
app.get('/', (req, res) => {
    res.sendFile(path.join(frontendPath, 'index.html'));
});

// POST 요청에 대한 처리
app.post('/hallo', async (req, res) => {
    const userMessage = req.body.message; // 프론트엔드에서 보낸 메시지 가져오기
    try {
        const hallo = await getChatCompletion(userMessage); // ChatGPT 응답을 받아 hallo에 저장
        res.json({ response: hallo }); // hallo 값을 JSON 형식으로 프론트엔드에 전달
    } catch (error) {
        res.status(500).json({ error: 'Error occurred while fetching the response.' });
    }
});

const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
    console.log(`Server is running on http://localhost:${PORT}`); // 서버 실행 확인 메시지
});
}
// 서버 시작
startServer();