I am been working on setting up a server in node.js and creating a website that can send and receive information from the server. This is my code
// server.js
const express = require('express');
const bodyParser = require('body-parser');
const cors = require('cors'); // Import the cors package
const { GoogleGenerativeAI } = require('@google/generative-ai');
const app = express();
const port = 3000;
const apiKey = 'MYAPIKEYTHATISCORRECT';
const genAI = new GoogleGenerativeAI(apiKey);
app.use(cors());
app.use(bodyParser.json());
app.post('/chat', async (req, res) => {
const { past_conversations } = req.body;
// Validate past_conversations structure
if (!Array.isArray(past_conversations) || !past_conversations.every(
convo => convo.role && convo.parts && Array.isArray(convo.parts) && convo.parts.every(part => part.text)
)) {
return res.status(400).json({ error: 'Invalid conversation structure' });
}
const userInputValue = past_conversations[past_conversations.length - 1].parts[0].text;
try {
const model = genAI.getGenerativeModel({
model: "gemini-1.5-pro",
systemInstruction: `Output the feelling for the sentence given, like happy, sad, fear or angry`,
});
const generationConfig = {
temperature: 0,
topP: 1,
topK: 128,
maxOutputTokens: 256,
responseMimeType: "text/plain",
};
const chatSession = model.startChat({
generationConfig,
history: past_conversations
});
const result = await chatSession.sendMessage(userInputValue);
const aiResponse = await result.response.text();
res.json({ output: aiResponse });
} catch (error) {
console.error('Error during chat processing:', error);
res.status(500).json({ error: 'Internal Server Error', details: error.message });
}
});
app.listen(port, () => {
console.log(`Server running at http://localhost:${port}/`);
});
// script.js
async function sendMessage() {
const userInputValue = userInput.value;
if (!userInputValue) return;
const chatDiv = document.getElementById('chat');
const userMessageDiv = document.createElement('div');
userMessageDiv.classList.add('message', 'user');
userMessageDiv.textContent = userInputValue;
chatDiv.appendChild(userMessageDiv);
chatDiv.scrollTop = chatDiv.scrollHeight;
userInput.value = '';
// Push user message to pastConversations
pastConversations.push({ role: "user", parts: [{ text: userInputValue }] });
try {
const response = await fetch('http://localhost:3000/chat', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({ past_conversations: pastConversations })
});
const data = await response.json();
if (!response.ok) {
throw new Error(data.error || 'Failed to get response from server');
}
const aiResponse = data.output;
const aiMessageDiv = document.createElement('div');
aiMessageDiv.classList.add('message', 'ai');
aiMessageDiv.textContent = aiResponse;
chatDiv.appendChild(aiMessageDiv);
chatDiv.scrollTop = chatDiv.scrollHeight;
// Push AI response to pastConversations
pastConversations.push({ role: "model", parts: [{ text: aiResponse }] });
aitext.push(aiResponse);
speak(aiResponse);
} catch (error) {
console.error('Error:', error);
}
}
After the function sendMessage() is called, I got the error 500 Internal Server Error and SyntaxError: Unexpected token ‘T’, “TypeError:”… is not valid JSON. What should I do to fix it? ChatGPT didn’t give any useful suggestions.