Building a chatbot, using a node server to make the fetch to the AI api, fetching to the node server. Everything works fine locally, but when I hosted the server on apprunner and added the URL to the frontend fetch, I get a 500.
I made sure the hosted server is working by making a GET another route on the same server.
This is the server
const { config } = require('dotenv');
config();
const apiKey = process.env.API_KEY;
const dbKey = process.env.DB_KEY;
const express = require('express');
const fetch = require('node-fetch');
const cors = require('cors');
const app = express();
const port = 3000;
app.use(cors());
app.use(express.json()); // Use express.json() for JSON parsing
app.post('/fetchData', async (req, res) => {
const inputValue = req.body.inputValue;
try {
const response = await fetch('https://clearai.net/api/database/query/v1', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': apiKey,
},
body: JSON.stringify({
msg: inputValue,
minLength: 1,
maxLength: 20,
stream: false,
model: 'gpt-4',
prompt: 'assistant',
dbKey: dbKey,
}),
});
const data = await response.json();
res.json(data);
} catch (error) {
console.error('Error:', error);
res.status(500).json({ error: 'Internal Server Error' });
}
});
app.listen(port, () => {
console.log(`Server is running on port ${port}`);
});
this is the frontend fetch
const handleSendClick = async () => {
if (inputValue.trim() !== '') {
const newMessages = [...messages, { type: 'user', text: inputValue }];
setMessages(newMessages);
setInputValue('');
setIsLoading(true);
try {
const serverResponse = await fetch('https://i5hp4qmqmk.us-east-1.awsapprunner.com/fetchData', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({ inputValue }),
});
if (serverResponse.ok) {
const data = await serverResponse.json();
const botReply = data.reply || 'No response from the bot.';
const botMessage = { type: 'bot', text: botReply };
setMessages([...newMessages, botMessage]);
} else {
console.error(
'Failed to fetch data from the server:',
serverResponse.statusText
);
}
} catch (error) {
console.error('Error fetching data from the server:', error);
} finally {
setIsLoading(false); // Reset loading state after the fetch
}
}
};