I am trying to integrate ChatGPT API and create a chatbot for my page using ReactJs and NodeJS.
There’s axios error and I don’t know why this isn’t working.
I am fairly new to ReactJS and NodeJS but I have a good understanding of JavaScript and Server side languages with database.
I tried installing various modules.
Also, what is the /chat path for? I don’t have such a file.
Here’s my backend and frontend code.
Please help me correct any syntax errors and let me know if you need any more details.
Openai.js in backend
import express from 'express';
import mysql from "mysql"
import cors from 'cors';
import bodyParser from 'body-parser';
import OpenAI from 'openai';
import 'dotenv/config'; // Ensure dotenv is imported to load environment variables
const openai = new OpenAI({apiKey: "key"});
// Setup server
const db = mysql.createConnection({
host: 'localhost',
user: 'root',
password: 'Effy1234',
database: 'nigger',
port: 3306
});
const app = express();
app.use(bodyParser.json());
app.use(cors());
// Endpoint for ChatGPT
app.post('/chat', async (req, res) => {
const { prompt } = req.body;
try {
const completion = await openai.completions.create({
model: 'text-davinci-003',
prompt: prompt,
max_tokens: 512,
temperature: 0,
});
res.send(completion.choices[0].text);
} catch (error) {
console.error('Error:', error);
res.status(500).send(error.message);
}
});
const PORT = process.env.PORT || 8000;
app.listen(PORT, () => {
console.log(`Server is running on port: ${PORT}`);
});
Chatbot.js in frontend
// src/components/chatbot.js
import React, { useState } from 'react';
import axios from 'axios';
import './chatbot.css';
const Chatbot = () => {
const [input, setInput] = useState('');
const [messages, setMessages] = useState([]);
const sendMessage = async () => {
if (!input.trim()) return;
const userMessage = { role: 'user', content: input };
setMessages([...messages, userMessage]);
console.log(input)
console.log(messages);
try {
const response = await axios.post('http://localhost:8000/chat', { prompt: input });
const botMessage = { role: 'bot', content: response.data };
console.log(botMessage);
setMessages([...messages, userMessage, botMessage]);
console.log(messages);
} catch (error) {
console.error('Error sending message:', error);
}
console.log(userMessage);
setInput('');
};
return (
<div className="chatbot-container">
<div className="chatbot-header">
<h2>Chatbot</h2>
</div>
<div className="chatbot-messages">
{messages.map((msg, index) => (
<div key={index} className={`chatbot-message ${msg.role}`}>
<strong>{msg.role === 'user' ? 'You' : 'Bot'}:</strong> {msg.content}
</div>
))}
</div>
<div className="chatbot-input-container">
<input
type="text"
value={input}
onChange={(e) => setInput(e.target.value)}
className="chatbot-input"
/>
<button onClick={sendMessage} className="chatbot-button">Send</button>
</div>
</div>
);
};
export default Chatbot;
Amit Bijlani is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.