chat-gpt api 적용중 CORS 문제

chat-gpt api 적용중 CORS 문제

QA

chat-gpt api 적용중 CORS 문제

답변 4

본문

그누보드에 chat-gpt를 적용하려는중인데요

CORS 에러가 나서 해결을 못하고 있습니다

고수님들 도움이나 힌트 부탁드립니다

 

먼저 제가 작성한 코드는 다음과 같습니다

★gnuboard5.5.8.2.6\theme\community\head.php


        <!-- chatGpt추가{ -->
        <form id="gpt-form" method="post">
            <div>
                <div><label for="prompt">Question to Chat-gpt:</label></div>
                <textarea id="prompt" name="prompt" cols="40" rows="3" required></textarea>
            </div>
            <div>
                <div><label for="response">Answer:</label></div>
                <textarea id="response" name="response" cols="40" rows="3" readonly></textarea>
            </div>
            <div>
                <input type="submit" value="Submit">
            </div>
        </form>
        <script>
            document.getElementById("gpt-form").addEventListener("submit", function(e) {
                e.preventDefault(); // 비동기통신용
 
                var prompt = document.getElementById("prompt").value;
 
                fetch('gpt-run.php', {
                        method: 'POST',
                        headers: {
                            'Content-Type': 'application/x-www-form-urlencoded',
                        },
                        body: 'prompt=' + encodeURIComponent(prompt),
                    })
                    .then(response => response.json())
                    .then(data => {
                        document.getElementById("response").value = data.response;
                    });
            });
        </script>
        <!-- chatGpt추가} -->

 

★C:\gnuboard5.5.8.2.6\theme\community\gpt-run.php


<?php
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $api_key = "***chat-gpt api key***"; // 발급받은 실제 키 사용중입니다
 
    $url = "https://api.openai.com/v1/completions";
 
    $prompt = filter_var($_POST["prompt"], FILTER_SANITIZE_FULL_SPECIAL_CHARS);
 
    $data = array(
        "model" => "text-davinci-003",
        "prompt" => $prompt,
        "max_tokens" => 3000,
        "temperature" => 0.5,
    );
 
    $data_string = json_encode($data);
 
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
    curl_setopt($ch, CURLOPT_HTTPHEADER, array(
        "Content-Type: application/json",
        "Authorization: Bearer $api_key",
        "Content-Length: " . strlen($data_string))
    );
 
    $output = curl_exec($ch);
    curl_close($ch);
 
    $output_json = json_decode($output, true);
    $response = $output_json["choices"][0]["text"];
 
    header('Content-Type: application/json');
    echo json_encode(array('response' => trim($response)));
 
    exit;
}
?>

 

그리고 제 그누보드 주소입니다

http://player0.dothome.co.kr/

 

알아보니까 헤더 추가하는법이 있어서 해봤는데 에러는 변함이 없네요

header("Access-Control-Allow-Origin: *");

 

그리고 같은 키로 gpt게시판에서 사용중인데 거기서는 동작에 문제가 없습니다

http://player0.dothome.co.kr/bbs/board.php?bo_table=gpt

 

도움 부탁드리겠습니다

이 질문에 댓글 쓰기 :

답변 4


<?php
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $api_key = "your-api-key"; // 실제 ChatGPT API 키로 대체
 
    $url = "https://api.openai.com/v1/completions";
 
    $prompt = filter_var($_POST["prompt"], FILTER_SANITIZE_FULL_SPECIAL_CHARS);
 
    $data = array(
        "model" => "text-davinci-003",
        "prompt" => $prompt,
        "max_tokens" => 3000,
        "temperature" => 0.5,
    );
 
    $data_string = json_encode($data);
 
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
    curl_setopt($ch, CURLOPT_HTTPHEADER, array(
        "Content-Type: application/json",
        "Authorization: Bearer $api_key",
        "Content-Length: " . strlen($data_string))
    );
 
    $output = curl_exec($ch);
 
    if ($output === false) {
        // 에러 처리
        $error = curl_error($ch);
        // 예를 들어, 로깅하거나 적절한 에러 응답을 반환하는 등의 처리를 수행할 수 있습니다.
        echo json_encode(array('response' => 'API request failed: ' . $error));
    } else {
        $output_json = json_decode($output, true);
        $response = $output_json["choices"][0]["text"];
     
        header('Content-Type: application/json');
        echo json_encode(array('response' => trim($response)));
    }
    curl_close($ch);
    exit;
}
?>

답변 감사드립니다

알려주신 코드를 추가 해 봤는데 서버가 아니라 클라이언트 쪽에서 발생하는 에러라서 브라우저에서는 받아볼수 없는것 같습니다. 아무것도 출력이 안되네요 ㅠㅠ

개발자 도구에는 아래의 에러가 출력되는데

2517186978_1684047920.7617.png

※Access to fetch at 'https://guide-page.dothome.co.kr/404.html' (redirected from 'http://player0.dothome.co.kr/gpt-run.php') from origin 'http://player0.dothome.co.kr' has been blocked by CORS policy: 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.
(index):261    

※GET https://guide-page.dothome.co.kr/404.html net::ERR_FAILED 200 (OK)
(anonymous) @ (index):261
(index):279

※Error: TypeError: Failed to fetch
    at HTMLFormElement.<anonymous> ((index):261:17)

 

화면이동없이 비동기통신으로 작성했다고 생각하는데 

'http://player0.dothome.co.kr/gpt-run.php'로 리다이렉트 하려는 것처럼 보입니다

뭐가 문제일까요

먼저 답변 감사합니다

제가 초보라서 검색하면서 하는중인데 php.ini파일 위치는 /etc/php.ini인거 같은데 파일질라에서 보면 etc라는 경로가 안보이네요

Configuration File (php.ini) Path /etc
Loaded Configuration File  /etc/php.ini

호스트는 닷홈에서 무료 호스팅 사용중인데 그게 문제일까요?

권한에 따라서 경로가 안보일수도 있다고 합니다

이런 경우 유료 도메인같은걸로 바꾸면 해결될지요?

답변을 작성하시기 전에 로그인 해주세요.
QA 내용 검색
질문등록
전체 125,873
© SIRSOFT
현재 페이지 제일 처음으로