Receivng and Sending JSON from node.js server to html

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

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<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}/`);
});
</code>
<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}/`); }); </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}/`);
});
Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>// 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);
}
}
</code>
<code>// 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); } } </code>
// 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.

1

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật