React + Axios ERR 401: 缺少 API 密钥

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

React + Axios ERR 401: Missing API key

问题

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

当前使用 axios 的代码:

  1. import React, { useState, useEffect } from "react";
  2. import { PaperAirplaneIcon } from "@heroicons/react/20/solid";
  3. import axios from "axios";
  4. import UserMessage from "./UserMessage";
  5. import BotMessage from "./BotMessage";
  6. const Chat = () => {
  7. const [messages, setMessages] = useState([]);
  8. const [inputValue, setInputValue] = useState("");
  9. const [loading, setLoading] = useState(false);
  10. const handleInputSubmit = async (e) => {
  11. e.preventDefault();
  12. setLoading(true);
  13. const userMessage = { type: "user", text: inputValue };
  14. setMessages([...messages, userMessage]);
  15. const botMessage = await getBotMessage(inputValue);
  16. setInputValue("");
  17. setMessages([...messages, botMessage]);
  18. setLoading(false);
  19. };
  20. const getBotMessage = async (userMessage) => {
  21. try {
  22. const response = await axios.post(
  23. "https://api.openai.com/v1/chat/completions",
  24. {
  25. messages: [
  26. { role: "system", content: "You are a helpful assistant." },
  27. { role: "user", content: userMessage },
  28. ],
  29. max_tokens: 256,
  30. n: 1,
  31. temperature: 0.85,
  32. model: "gpt-3.5-turbo",
  33. },
  34. {
  35. headers: {
  36. "Content-Type": "application/json",
  37. Authorization: `Bearer ${process.env.REACT_APP_OPENAI_API_KEY}`,
  38. },
  39. }
  40. );
  41. //console.log("response", response.data.choices[0].text);
  42. const botMessage = { type: "bot", text: response.data.choices[0].text };
  43. return botMessage;
  44. } catch (e) {
  45. console.log(e);
  46. const botMessage = {
  47. type: "bot",
  48. text: "Something went wrong. Try again.",
  49. };
  50. return botMessage;
  51. }
  52. };
  53. return (
  54. <div className="flex flex-col items-center w-full h-full justify-between">
  55. <h1 className="text-3xl font-bold my-5">Chatbot</h1>
  56. <div className="w-full">
  57. {messages.map((message, index) => {
  58. if (message.type === "user") {
  59. return <UserMessage key={index} text={message.text} />;
  60. }
  61. return <BotMessage key={index} text={message.text} />;
  62. })}
  63. <form
  64. onSubmit={handleInputSubmit}
  65. className="flex flex-row w-full mb-5 mt-2"
  66. >
  67. <input
  68. className="border-2 rounded-md p-2 w-full"
  69. type="text"
  70. value={inputValue}
  71. onChange={(e) => setInputValue(e.target.value)}
  72. />
  73. <button type="submit">
  74. <PaperAirplaneIcon className="w-6 h-6 text-green-500" />
  75. </button>
  76. </form>
  77. </div>
  78. </div>
  79. );
  80. };
  81. export default Chat;

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

  1. import React, { useState, useEffect } from "react";
  2. import { PaperAirplaneIcon } from "@heroicons/react/20/solid";
  3. import axios from "axios";
  4. import UserMessage from "./UserMessage";
  5. import BotMessage from "./BotMessage";
  6. const { Configuration, OpenAIApi } = require("openai");
  7. const Chat = () => {
  8. const [messages, setMessages] = useState([]);
  9. const [inputValue, setInputValue] = useState("");
  10. const [loading, setLoading] = useState(false);
  11. const configuration = new Configuration({
  12. apiKey: process.env.REACT_APP_OPENAI_API_KEY,
  13. });
  14. const openai = new OpenAIApi(configuration);
  15. const handleInputSubmit = async (e) => {
  16. e.preventDefault();
  17. setLoading(true);
  18. const userMessage = { type: "user", text: inputValue };
  19. setMessages([...messages, userMessage]);
  20. const botMessage = await getBotMessage(inputValue);
  21. setInputValue("");
  22. setMessages([...messages, botMessage]);
  23. setLoading(false);
  24. };
  25. const getBotMessage = async (userMessage) => {
  26. try {
  27. const response = await openai.createCompletion({
  28. model: "gpt-3.5-turbo",
  29. prompt: userMessage,
  30. temperature: 0.85,
  31. max_tokens: 4000,
  32. });
  33. //console.log("response", response.data.choices[0].text);
  34. const botMessage = { type: "bot", text: response.data.choices[0].text };
  35. return botMessage;
  36. } catch (e) {
  37. console.log(e);
  38. const botMessage = {
  39. type: "bot",
  40. text: "Something went wrong. Try again.",
  41. };
  42. return botMessage;
  43. }
  44. };
  45. return (
  46. <div className="flex flex-col items-center w-full h-full justify-between">
  47. <h1 className="text-3xl font-bold my-5">Golfdommer</h1>
  48. <div className="w-full">
  49. {messages.map((message, index) => {
  50. if (message.type === "user") {
  51. return <UserMessage key={index} text={message.text} />;
  52. }
  53. return <BotMessage key={index} text={message.text} />;
  54. })}
  55. <form
  56. onSubmit={handleInputSubmit}
  57. className="flex flex-row w-full mb-5 mt-2"
  58. >
  59. <input
  60. className="border-2 rounded-md p-2 w-full"
  61. type="text"
  62. value={inputValue}
  63. onChange={(e) => setInputValue(e.target.value)}
  64. />
  65. <button type="submit">
  66. <PaperAirplaneIcon className="w-6 h-6 text-green-500" />
  67. </button>
  68. </form>
  69. </div>
  70. </div>
  71. );
  72. };
  73. 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:

  1. import React, { useState, useEffect } from &quot;react&quot;;
  2. import { PaperAirplaneIcon } from &quot;@heroicons/react/20/solid&quot;;
  3. import axios from &quot;axios&quot;;
  4. import UserMessage from &quot;./UserMessage&quot;;
  5. import BotMessage from &quot;./BotMessage&quot;;
  6. const Chat = () =&gt; {
  7. const [messages, setMessages] = useState([]);
  8. const [inputValue, setInputValue] = useState(&quot;&quot;);
  9. const [loading, setLoading] = useState(false);
  10. const handleInputSubmit = async (e) =&gt; {
  11. e.preventDefault();
  12. setLoading(true);
  13. const userMessage = { type: &quot;user&quot;, text: inputValue };
  14. setMessages([...messages, userMessage]);
  15. const botMessage = await getBotMessage(inputValue);
  16. setInputValue(&quot;&quot;);
  17. setMessages([...messages, botMessage]);
  18. setLoading(false);
  19. };
  20. const getBotMessage = async (userMessage) =&gt; {
  21. try {
  22. const response = await axios.post(
  23. &quot;https://api.openai.com/v1/chat/completions&quot;,
  24. {
  25. messages: [
  26. { role: &quot;system&quot;, content: &quot;You are a helpful assistant.&quot; },
  27. { role: &quot;user&quot;, content: userMessage },
  28. ],
  29. max_tokens: 256,
  30. n: 1,
  31. temperature: 0.85,
  32. model: &quot;gpt-3.5-turbo&quot;,
  33. },
  34. {
  35. headers: {
  36. &quot;Content-Type&quot;: &quot;application/json&quot;,
  37. Authorization: `Bearer ${process.env.REACT_APP_OPENAI_API_KEY}`,
  38. },
  39. }
  40. );
  41. //console.log(&quot;response&quot;, response.data.choices[0].text);
  42. const botMessage = { type: &quot;bot&quot;, text: response.data.choices[0].text };
  43. return botMessage;
  44. } catch (e) {
  45. console.log(e);
  46. const botMessage = {
  47. type: &quot;bot&quot;,
  48. text: &quot;Something went wrong. Try again.&quot;,
  49. };
  50. return botMessage;
  51. }
  52. };
  53. return (
  54. &lt;div className=&quot;flex flex-col items-center w-full h-full justify-between&quot;&gt;
  55. &lt;h1 className=&quot;text-3xl font-bold my-5&quot;&gt;Chatbot&lt;/h1&gt;
  56. &lt;div className=&quot;w-full&quot;&gt;
  57. {messages.map((message, index) =&gt; {
  58. if (message.type === &quot;user&quot;) {
  59. return &lt;UserMessage key={index} text={message.text} /&gt;;
  60. }
  61. return &lt;BotMessage key={index} text={message.text} /&gt;;
  62. })}
  63. &lt;form
  64. onSubmit={handleInputSubmit}
  65. className=&quot;flex flex-row w-full mb-5 mt-2&quot;
  66. &gt;
  67. &lt;input
  68. className=&quot;border-2 rounded-md p-2 w-full&quot;
  69. type=&quot;text&quot;
  70. value={inputValue}
  71. onChange={(e) =&gt; setInputValue(e.target.value)}
  72. /&gt;
  73. &lt;button type=&quot;submit&quot;&gt;
  74. &lt;PaperAirplaneIcon className=&quot;w-6 h-6 text-green-500&quot; /&gt;
  75. &lt;/button&gt;
  76. &lt;/form&gt;
  77. &lt;/div&gt;
  78. &lt;/div&gt;
  79. );
  80. };
  81. export default Chat;

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

  1. import React, { useState, useEffect } from &quot;react&quot;;
  2. import { PaperAirplaneIcon } from &quot;@heroicons/react/20/solid&quot;;
  3. import axios from &quot;axios&quot;;
  4. import UserMessage from &quot;./UserMessage&quot;;
  5. import BotMessage from &quot;./BotMessage&quot;;
  6. const { Configuration, OpenAIApi } = require(&quot;openai&quot;);
  7. const Chat = () =&gt; {
  8. const [messages, setMessages] = useState([]);
  9. const [inputValue, setInputValue] = useState(&quot;&quot;);
  10. const [loading, setLoading] = useState(false);
  11. const configuration = new Configuration({
  12. apiKey: process.env.REACT_APP_OPENAI_API_KEY,
  13. });
  14. const openai = new OpenAIApi(configuration);
  15. const handleInputSubmit = async (e) =&gt; {
  16. e.preventDefault();
  17. setLoading(true);
  18. const userMessage = { type: &quot;user&quot;, text: inputValue };
  19. setMessages([...messages, userMessage]);
  20. const botMessage = await getBotMessage(inputValue);
  21. setInputValue(&quot;&quot;);
  22. setMessages([...messages, botMessage]);
  23. setLoading(false);
  24. };
  25. const getBotMessage = async (userMessage) =&gt; {
  26. try {
  27. const response = await openai.createCompletion({
  28. model: &quot;gpt-3.5-turbo&quot;,
  29. prompt: userMessage,
  30. temperature: 0.85,
  31. max_tokens: 4000,
  32. });
  33. //console.log(&quot;response&quot;, response.data.choices[0].text);
  34. const botMessage = { type: &quot;bot&quot;, text: response.data.choices[0].text };
  35. return botMessage;
  36. } catch (e) {
  37. console.log(e);
  38. const botMessage = {
  39. type: &quot;bot&quot;,
  40. text: &quot;Something went wrong. Try again.&quot;,
  41. };
  42. return botMessage;
  43. }
  44. };
  45. return (
  46. &lt;div className=&quot;flex flex-col items-center w-full h-full justify-between&quot;&gt;
  47. &lt;h1 className=&quot;text-3xl font-bold my-5&quot;&gt;Golfdommer&lt;/h1&gt;
  48. &lt;div className=&quot;w-full&quot;&gt;
  49. {messages.map((message, index) =&gt; {
  50. if (message.type === &quot;user&quot;) {
  51. return &lt;UserMessage key={index} text={message.text} /&gt;;
  52. }
  53. return &lt;BotMessage key={index} text={message.text} /&gt;;
  54. })}
  55. &lt;form
  56. onSubmit={handleInputSubmit}
  57. className=&quot;flex flex-row w-full mb-5 mt-2&quot;
  58. &gt;
  59. &lt;input
  60. className=&quot;border-2 rounded-md p-2 w-full&quot;
  61. type=&quot;text&quot;
  62. value={inputValue}
  63. onChange={(e) =&gt; setInputValue(e.target.value)}
  64. /&gt;
  65. &lt;button type=&quot;submit&quot;&gt;
  66. &lt;PaperAirplaneIcon className=&quot;w-6 h-6 text-green-500&quot; /&gt;
  67. &lt;/button&gt;
  68. &lt;/form&gt;
  69. &lt;/div&gt;
  70. &lt;/div&gt;
  71. );
  72. };
  73. 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文件中,将构建脚本更改如下:

  1. &quot;scripts&quot;: {
  2. &quot;start&quot;: &quot;env-cmd -f .env.staging react-scripts start&quot;,
  3. &quot;build:staging&quot;: &quot;env-cmd -f .env.staging react-scripts build&quot;,
  4. &quot;build:production&quot;: &quot;env-cmd -f .env.production react-scripts build&quot;,
  5. &quot;test&quot;: &quot;react-scripts test&quot;,
  6. &quot;eject&quot;: &quot;react-scripts eject&quot;
  7. },

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

  1. &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:

  1. &quot;scripts&quot;: {
  2. &quot;start&quot;: &quot;env-cmd -f .env.staging react-scripts start&quot;,
  3. &quot;build:staging&quot;: &quot;env-cmd -f .env.staging react-scripts build&quot;,
  4. &quot;build:production&quot;: &quot;env-cmd -f .env.production react-scripts build&quot;,
  5. &quot;test&quot;: &quot;react-scripts test&quot;,
  6. &quot;eject&quot;: &quot;react-scripts eject&quot;
  7. },

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,

  1. &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
匿名

发表评论

匿名网友

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

确定