Search code examples
javascriptnode.jsreactjsviteopenai-api

Image not loading and API failing with 401 error on production build using Vite


I am using Vite for my React project and encountering a couple of issues when I run the production build.

  1. I have an image in my React component, which is loading perfectly fine when I run npm run dev. However, when I build the project using npm run build and then preview it using npm run preview, the image does not load and I see a 404 error in the console for the image file /src/assets/king.png. Here's the relevant code snippet:
<img src="./src/assets/king.png" height={210} alt="logo" className="logo" />
  1. I am also making a POST request to OpenAI API ↗ using Axios. This works fine in development, but in production, I am getting a 401 Unauthorized error. Here's the relevant code snippet:
import { Configuration, OpenAIApi } from "openai";

const config = new Configuration({
  apiKey: "MY_KEY",
});

const openai = new OpenAIApi(config);

const generateQuestions = async (topic, language) => {
  const response = await openai.createChatCompletion({
    model: "gpt-3.5-turbo",
    messages: [
      {
        role: "system",
        content: "You are a helpful assistant that generates trivia questions.",
      },
      {
        role: "user",
        content: `Generate trivia question on the topic of ${topic} in ${language} language with a definitive answer and 3 incorrect answers in the following JSON format:`,
      },
    ],
    temperature: 0.7,
    max_tokens: 256,
    n: 10, 
  });

  const generatedQuestions = response.data.choices.map((choice) => {
    const questionJSON = JSON.parse(choice.message.content);
    return questionJSON;
  });

  console.log(generatedQuestions);
  return generatedQuestions;
};

I've already ensured that the OpenAI API key is correct and it works in development. I've also tried varying the file path for the image, but without success. Any help on these two issues would be greatly appreciated!


Remember to replace the API key in your code with a placeholder before posting the question, as sharing the real key in public is a security risk. You should also regenerate your API key if it has been exposed.


Solution

  • Try this:

    1. Import your image i.e.
    import king from "./src/assets/king.png";
    <img src={king} height={210} alt="logo" className="logo" />