React + Axios ERR 401: 缺少 API 密钥

huangapple go评论70阅读模式
英文:

React + Axios ERR 401: Missing API key

问题

以下是您提供的代码的翻译部分:

当前使用 axios 的代码:

import React, { useState, useEffect } from "react";
import { PaperAirplaneIcon } from "@heroicons/react/20/solid";
import axios from "axios";
import UserMessage from "./UserMessage";
import BotMessage from "./BotMessage";

const Chat = () => {
  const [messages, setMessages] = useState([]);
  const [inputValue, setInputValue] = useState("");
  const [loading, setLoading] = useState(false);

  const handleInputSubmit = async (e) => {
    e.preventDefault();
    setLoading(true);
    const userMessage = { type: "user", text: inputValue };
    setMessages([...messages, userMessage]);
    const botMessage = await getBotMessage(inputValue);
    setInputValue("");
    setMessages([...messages, botMessage]);
    setLoading(false);
  };

  const getBotMessage = async (userMessage) => {
    try {
      const response = await axios.post(
        "https://api.openai.com/v1/chat/completions",
        {
          messages: [
            { role: "system", content: "You are a helpful assistant." },
            { role: "user", content: userMessage },
          ],
          max_tokens: 256,
          n: 1,
          temperature: 0.85,
          model: "gpt-3.5-turbo",
        },
        {
          headers: {
            "Content-Type": "application/json",
            Authorization: `Bearer ${process.env.REACT_APP_OPENAI_API_KEY}`,
          },
        }
      );
      //console.log("response", response.data.choices[0].text);
      const botMessage = { type: "bot", text: response.data.choices[0].text };
      return botMessage;
    } catch (e) {
      console.log(e);
      const botMessage = {
        type: "bot",
        text: "Something went wrong. Try again.",
      };
      return botMessage;
    }
  };

  return (
    <div className="flex flex-col items-center w-full h-full justify-between">
      <h1 className="text-3xl font-bold my-5">Chatbot</h1>
      <div className="w-full">
        {messages.map((message, index) => {
          if (message.type === "user") {
            return <UserMessage key={index} text={message.text} />;
          }
          return <BotMessage key={index} text={message.text} />;
        })}
        <form
          onSubmit={handleInputSubmit}
          className="flex flex-row w-full mb-5 mt-2"
        >
          <input
            className="border-2 rounded-md p-2 w-full"
            type="text"
            value={inputValue}
            onChange={(e) => setInputValue(e.target.value)}
          />
          <button type="submit">
            <PaperAirplaneIcon className="w-6 h-6 text-green-500" />
          </button>
        </form>
      </div>
    </div>
  );
};

export default Chat;

这是使用 openai(不是当前代码)的尝试:

import React, { useState, useEffect } from "react";
import { PaperAirplaneIcon } from "@heroicons/react/20/solid";
import axios from "axios";
import UserMessage from "./UserMessage";
import BotMessage from "./BotMessage";
const { Configuration, OpenAIApi } = require("openai");

const Chat = () => {
  const [messages, setMessages] = useState([]);
  const [inputValue, setInputValue] = useState("");
  const [loading, setLoading] = useState(false);

  const configuration = new Configuration({
    apiKey: process.env.REACT_APP_OPENAI_API_KEY,
  });
  const openai = new OpenAIApi(configuration);

  const handleInputSubmit = async (e) => {
    e.preventDefault();
    setLoading(true);
    const userMessage = { type: "user", text: inputValue };
    setMessages([...messages, userMessage]);
    const botMessage = await getBotMessage(inputValue);
    setInputValue("");
    setMessages([...messages, botMessage]);
    setLoading(false);
  };

  const getBotMessage = async (userMessage) => {
    try {
      const response = await openai.createCompletion({
        model: "gpt-3.5-turbo",
        prompt: userMessage,
        temperature: 0.85,
        max_tokens: 4000,
      });
      //console.log("response", response.data.choices[0].text);
      const botMessage = { type: "bot", text: response.data.choices[0].text };
      return botMessage;
    } catch (e) {
      console.log(e);
      const botMessage = {
        type: "bot",
        text: "Something went wrong. Try again.",
      };
      return botMessage;
    }
  };

  return (
    <div className="flex flex-col items-center w-full h-full justify-between">
      <h1 className="text-3xl font-bold my-5">Golfdommer</h1>
      <div className="w-full">
        {messages.map((message, index) => {
          if (message.type === "user") {
            return <UserMessage key={index} text={message.text} />;
          }
          return <BotMessage key={index} text={message.text} />;
        })}
        <form
          onSubmit={handleInputSubmit}
          className="flex flex-row w-full mb-5 mt-2"
        >
          <input
            className="border-2 rounded-md p-2 w-full"
            type="text"
            value={inputValue}
            onChange={(e) => setInputValue(e.target.value)}
          />
          <button type="submit">
            <PaperAirplaneIcon className="w-6 h-6 text-green-500" />
          </button>
        </form>
      </div>
    </div>
  );
};

export default Chat;

希望这有所帮助。如果您有任何其他问题,请随时提问。

英文:

I am learning React and I am trying to create a specialized chatbot using the ChatGPT API along the way. At the moment I am just trying to get a response from the API using axios. I have my API key in a .env, yet I am still getting a 401 error indicating that I need to provide an API key. It works if I hardcode the API key, so there must be some error in reading from the .env. You can find my code for the Chat functionality below.

I initially tried using the openai package along with the createCompletion() method, but that gave an error saying Refused to set unsafe header &quot;User Agent&quot;, which I didn't quite understand, so I opted for the current approach. I will provide the code for my attempt with openai at the bottom.

Any help is appreciated, thanks.

Current code using axios:

import React, { useState, useEffect } from &quot;react&quot;;
import { PaperAirplaneIcon } from &quot;@heroicons/react/20/solid&quot;;
import axios from &quot;axios&quot;;
import UserMessage from &quot;./UserMessage&quot;;
import BotMessage from &quot;./BotMessage&quot;;
const Chat = () =&gt; {
const [messages, setMessages] = useState([]);
const [inputValue, setInputValue] = useState(&quot;&quot;);
const [loading, setLoading] = useState(false);
const handleInputSubmit = async (e) =&gt; {
e.preventDefault();
setLoading(true);
const userMessage = { type: &quot;user&quot;, text: inputValue };
setMessages([...messages, userMessage]);
const botMessage = await getBotMessage(inputValue);
setInputValue(&quot;&quot;);
setMessages([...messages, botMessage]);
setLoading(false);
};
const getBotMessage = async (userMessage) =&gt; {
try {
const response = await axios.post(
&quot;https://api.openai.com/v1/chat/completions&quot;,
{
messages: [
{ role: &quot;system&quot;, content: &quot;You are a helpful assistant.&quot; },
{ role: &quot;user&quot;, content: userMessage },
],
max_tokens: 256,
n: 1,
temperature: 0.85,
model: &quot;gpt-3.5-turbo&quot;,
},
{
headers: {
&quot;Content-Type&quot;: &quot;application/json&quot;,
Authorization: `Bearer ${process.env.REACT_APP_OPENAI_API_KEY}`,
},
}
);
//console.log(&quot;response&quot;, response.data.choices[0].text);
const botMessage = { type: &quot;bot&quot;, text: response.data.choices[0].text };
return botMessage;
} catch (e) {
console.log(e);
const botMessage = {
type: &quot;bot&quot;,
text: &quot;Something went wrong. Try again.&quot;,
};
return botMessage;
}
};
return (
&lt;div className=&quot;flex flex-col items-center w-full h-full justify-between&quot;&gt;
&lt;h1 className=&quot;text-3xl font-bold my-5&quot;&gt;Chatbot&lt;/h1&gt;
&lt;div className=&quot;w-full&quot;&gt;
{messages.map((message, index) =&gt; {
if (message.type === &quot;user&quot;) {
return &lt;UserMessage key={index} text={message.text} /&gt;;
}
return &lt;BotMessage key={index} text={message.text} /&gt;;
})}
&lt;form
onSubmit={handleInputSubmit}
className=&quot;flex flex-row w-full mb-5 mt-2&quot;
&gt;
&lt;input
className=&quot;border-2 rounded-md p-2 w-full&quot;
type=&quot;text&quot;
value={inputValue}
onChange={(e) =&gt; setInputValue(e.target.value)}
/&gt;
&lt;button type=&quot;submit&quot;&gt;
&lt;PaperAirplaneIcon className=&quot;w-6 h-6 text-green-500&quot; /&gt;
&lt;/button&gt;
&lt;/form&gt;
&lt;/div&gt;
&lt;/div&gt;
);
};
export default Chat;

This was my attempt using openai (not my current code):

import React, { useState, useEffect } from &quot;react&quot;;
import { PaperAirplaneIcon } from &quot;@heroicons/react/20/solid&quot;;
import axios from &quot;axios&quot;;
import UserMessage from &quot;./UserMessage&quot;;
import BotMessage from &quot;./BotMessage&quot;;
const { Configuration, OpenAIApi } = require(&quot;openai&quot;);
const Chat = () =&gt; {
const [messages, setMessages] = useState([]);
const [inputValue, setInputValue] = useState(&quot;&quot;);
const [loading, setLoading] = useState(false);
const configuration = new Configuration({
apiKey: process.env.REACT_APP_OPENAI_API_KEY,
});
const openai = new OpenAIApi(configuration);
const handleInputSubmit = async (e) =&gt; {
e.preventDefault();
setLoading(true);
const userMessage = { type: &quot;user&quot;, text: inputValue };
setMessages([...messages, userMessage]);
const botMessage = await getBotMessage(inputValue);
setInputValue(&quot;&quot;);
setMessages([...messages, botMessage]);
setLoading(false);
};
const getBotMessage = async (userMessage) =&gt; {
try {
const response = await openai.createCompletion({
model: &quot;gpt-3.5-turbo&quot;,
prompt: userMessage,
temperature: 0.85,
max_tokens: 4000,
});
//console.log(&quot;response&quot;, response.data.choices[0].text);
const botMessage = { type: &quot;bot&quot;, text: response.data.choices[0].text };
return botMessage;
} catch (e) {
console.log(e);
const botMessage = {
type: &quot;bot&quot;,
text: &quot;Something went wrong. Try again.&quot;,
};
return botMessage;
}
};
return (
&lt;div className=&quot;flex flex-col items-center w-full h-full justify-between&quot;&gt;
&lt;h1 className=&quot;text-3xl font-bold my-5&quot;&gt;Golfdommer&lt;/h1&gt;
&lt;div className=&quot;w-full&quot;&gt;
{messages.map((message, index) =&gt; {
if (message.type === &quot;user&quot;) {
return &lt;UserMessage key={index} text={message.text} /&gt;;
}
return &lt;BotMessage key={index} text={message.text} /&gt;;
})}
&lt;form
onSubmit={handleInputSubmit}
className=&quot;flex flex-row w-full mb-5 mt-2&quot;
&gt;
&lt;input
className=&quot;border-2 rounded-md p-2 w-full&quot;
type=&quot;text&quot;
value={inputValue}
onChange={(e) =&gt; setInputValue(e.target.value)}
/&gt;
&lt;button type=&quot;submit&quot;&gt;
&lt;PaperAirplaneIcon className=&quot;w-6 h-6 text-green-500&quot; /&gt;
&lt;/button&gt;
&lt;/form&gt;
&lt;/div&gt;
&lt;/div&gt;
);
};
export default Chat;

答案1

得分: 1

If you have created your React app using create-react-app then you could do the following to configure your API key using environment variables (.env):

  1. 使用npm安装env-cmd包。

  2. 在项目根目录创建名为.env.envName的文件,例如,对于暂存环境,您可以将其命名为.env.staging.env.production等,以区分每个环境中的变量。

  3. 在env文件中以REACT_APP为前缀,以键/值表示法添加您的变量,如下所示:

    REACT_APP_API_KEY = "****"

在您的package.json文件中,将构建脚本更改如下:

&quot;scripts&quot;: {
&quot;start&quot;: &quot;env-cmd -f .env.staging react-scripts start&quot;,
&quot;build:staging&quot;: &quot;env-cmd -f .env.staging react-scripts build&quot;,
&quot;build:production&quot;: &quot;env-cmd -f .env.production react-scripts build&quot;,
&quot;test&quot;: &quot;react-scripts test&quot;,
&quot;eject&quot;: &quot;react-scripts eject&quot;
},

注意: -f标志用于自定义env文件路径,默认情况下在项目根目录中,否则您应该指定实际路径。例如,

&quot;start&quot;: &quot;env-cmd -f ../../.env.staging react-scripts start&quot;,

关于您的错误Refused to set unsafe header &quot;User Agent&quot;,我建议您查看这个链接

希望这有所帮助。

英文:

If you have created your React app using create-react-app then you could do the following to configure your API key using environment variables (.env)

  1. Install env-cmd package from npm

  2. Make a file called .env.envName in your project root, For example: For staging you can name it as .env.staging, .env.production and so on to differentiate between variables in each environment.

  3. Inside the env file add your variables in key/value representation with prefix of REACT_APP as follows:

    REACT_APP_API_KEY = "****"

Inside your package.json. change the build scripts as follows:

&quot;scripts&quot;: {
&quot;start&quot;: &quot;env-cmd -f .env.staging react-scripts start&quot;,
&quot;build:staging&quot;: &quot;env-cmd -f .env.staging react-scripts build&quot;,
&quot;build:production&quot;: &quot;env-cmd -f .env.production react-scripts build&quot;,
&quot;test&quot;: &quot;react-scripts test&quot;,
&quot;eject&quot;: &quot;react-scripts eject&quot;
},

Note: -f flag is for custom env file paths as the default is in the project root otherwise you should specify the actual path. For example,

&quot;start&quot;: &quot;env-cmd -f ../../.env.staging react-scripts start&quot;,

Regarding your error Refused to set unsafe header &quot;User Agent&quot;, I would suggest you to have a look at this link.

Hope that helps.

huangapple
  • 本文由 发表于 2023年4月19日 16:36:41
  • 转载请务必保留本文链接:https://go.coder-hub.com/76052378.html
  • axios
  • http-status-code-401
  • javascript
  • openai-api
  • reactjs

如何在没有填充的情况下,从文本到

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定