Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Cors Error #13

Closed
lesquive opened this issue Mar 1, 2024 · 2 comments
Closed

Cors Error #13

lesquive opened this issue Mar 1, 2024 · 2 comments

Comments

@lesquive
Copy link

lesquive commented Mar 1, 2024

Hello!

I'm having issues with a Cors error being generated on by browser when I attempt to access Milua using a React client on local host. I'm unable to find any documentation on how to fix this. Any ideas?

This is my current script:

local app = require "milua"
local http = require("socket.http")
local ltn12 = require("ltn12")
local cjson = require("cjson")

local config = dofile("config.lua")
local openaiApiKey = config.openaiApiKey

-- API endpoint
local apiUrl = "https://api.openai.com/v1/chat/completions"

app.add_handler(
    "POST",
    "/openai",
    function(captures, query, headers, body)

        if headers["method"] == "OPTIONS" then
            return "", 200, {
                ["Access-Control-Allow-Origin"] = "*", -- Allow requests from any origin
                ["Access-Control-Allow-Methods"] = "POST, OPTIONS", -- Allow POST and OPTIONS methods
                ["Access-Control-Allow-Headers"] = "Content-Type, Authorization" -- Allow specified headers
            }
        end

        -- Parse JSON from the request body
        local requestData = {
            model = "gpt-3.5-turbo",
            messages = {{role = "user", content = cjson.decode(body).content}},
            temperature = 0.7
        }

        print("Request:", requestData)

        -- Convert Lua table to JSON
        local requestBody = cjson.encode(requestData)

        print("RequestBB:", requestBody)

        -- Request headers
        local requestHeaders = {
            ["Content-Type"] = "application/json",
            ["Authorization"] = "Bearer " .. openaiApiKey
        }

        -- Perform HTTP request
        local response = {}
        local _, statusCode, _, _ = http.request{
            url = apiUrl,
            method = "POST",
            headers = requestHeaders,
            source = ltn12.source.string(requestBody),
            sink = ltn12.sink.table(response)
        }

        -- Check the response
        if statusCode == 200 then
            print("Made it here!")
            local responseBody = table.concat(response)
            print("responseBody", responseBody)
            return responseBody 
        else
            return "Error"
        end
    end
)

app.start()

The error message I get:

image

My client is just doing a POST via axios:

const response = await axios.post("http://localhost:8800/openai", {
        content: input,
      });
@lesquive
Copy link
Author

lesquive commented Mar 1, 2024

Update, I was able to fix the code with the following:

local app = require "milua"
local http = require("socket.http")
local ltn12 = require("ltn12")
local cjson = require("cjson")

-- Your OpenAI API key
local config = dofile("config.lua")
local openaiApiKey = config.openaiApiKey

-- API endpoint
local apiUrl = "https://api.openai.com/v1/chat/completions"

-- Define a handler for the OPTIONS method
app.add_handler(
    "OPTIONS",
    "/openai",
    function(captures, query, headers, body)

        -- Respond to preflight requests
        return "", {
            ["Access-Control-Allow-Origin"] = "*", -- Allow requests from any origin
            ["Access-Control-Allow-Methods"] = "POST, OPTIONS", -- Allow POST and OPTIONS methods
            ["Access-Control-Allow-Headers"] = "Content-Type, Authorization" -- Allow specified headers
        }
    end
)

-- Define a handler for the "/openai" endpoint
app.add_handler(
    "POST",
    "/openai",
    function(captures, query, headers, body)
        -- Parse JSON from the request body
        local requestData = {
            model = "gpt-3.5-turbo",
            messages = {{role = "user", content = cjson.decode(body).content}},
            temperature = 0.7
        }

        print("Request:", requestData)

        -- Convert Lua table to JSON
        local requestBody = cjson.encode(requestData)

        print("RequestBB:", requestBody)

        -- Request headers
        local requestHeaders = {
            ["Content-Type"] = "application/json",
            ["Authorization"] = "Bearer " .. openaiApiKey
        }

        -- Perform HTTP request
        local response = {}
        local _, statusCode, _, _ = http.request{
            url = apiUrl,
            method = "POST",
            headers = requestHeaders,
            source = ltn12.source.string(requestBody),
            sink = ltn12.sink.table(response)
        }

        -- Check the response
        if statusCode == 200 then
            print("Made it here!")
            local responseBody = table.concat(response)
            print("responseBody", responseBody)
            return responseBody, {
                ["Access-Control-Allow-Origin"] = "*", -- Allow requests from any origin
                ["Access-Control-Allow-Methods"] = "POST, OPTIONS", -- Allow POST and OPTIONS methods
                ["Access-Control-Allow-Headers"] = "Content-Type, Authorization" -- Allow specified headers
            } 
        else
            return "Error", {
                ["Access-Control-Allow-Origin"] = "*", -- Allow requests from any origin
                ["Access-Control-Allow-Methods"] = "POST, OPTIONS", -- Allow POST and OPTIONS methods
                ["Access-Control-Allow-Headers"] = "Content-Type, Authorization" -- Allow specified headers
            }
        end
    end
)

-- Start the application
app.start()

Not sure if its the best solution, but it works!

@MiguelMJ
Copy link
Owner

MiguelMJ commented Mar 4, 2024

Glad you found a solution!
CORS errors compete the browser and the configuration of the responses, not the framework itself.
Check this as reference.
Thanks for reporting anyways!

@MiguelMJ MiguelMJ closed this as completed Mar 4, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants