英文:
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 "User Agent"
, 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 "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;
This was my attempt using openai
(not my current code):
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;
答案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)
:
-
使用npm安装env-cmd包。
-
在项目根目录创建名为
.env.envName
的文件,例如,对于暂存环境,您可以将其命名为.env.staging
,.env.production
等,以区分每个环境中的变量。 -
在env文件中以
REACT_APP
为前缀,以键/值表示法添加您的变量,如下所示:REACT_APP_API_KEY = "****"
在您的package.json文件中,将构建脚本更改如下:
"scripts": {
"start": "env-cmd -f .env.staging react-scripts start",
"build:staging": "env-cmd -f .env.staging react-scripts build",
"build:production": "env-cmd -f .env.production react-scripts build",
"test": "react-scripts test",
"eject": "react-scripts eject"
},
注意: -f
标志用于自定义env文件路径,默认情况下在项目根目录中,否则您应该指定实际路径。例如,
"start": "env-cmd -f ../../.env.staging react-scripts start",
关于您的错误Refused to set unsafe header "User Agent"
,我建议您查看这个链接。
希望这有所帮助。
英文:
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)
-
Install env-cmd package from npm
-
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. -
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:
"scripts": {
"start": "env-cmd -f .env.staging react-scripts start",
"build:staging": "env-cmd -f .env.staging react-scripts build",
"build:production": "env-cmd -f .env.production react-scripts build",
"test": "react-scripts test",
"eject": "react-scripts eject"
},
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,
"start": "env-cmd -f ../../.env.staging react-scripts start",
Regarding your error Refused to set unsafe header "User Agent"
, I would suggest you to have a look at this link.
Hope that helps.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论