3. Introduction to Web Backend Using JavaScript
Setting Up a Simple Node.js Server
Initialize a Node.js Project:
npm init -yInstall Express:
npm install expressCreate a Simple Server:
Create
server.js:
const express = require('express'); const app = express(); const port = 5000; app.get('/', (req, res) => { res.send('Hello from the backend!'); }); app.listen(port, () => { console.log(`Server running at http://localhost:${port}`); });Run the server:
node server.js
Connecting Backend with GenAI API
Install Axios:
npm install axiosCreate an Endpoint to Call GenAI:
Update
server.js:
const axios = require('axios'); app.post('/chat', async (req, res) => { const response = await axios.post('https://api.openai.com/v1/chat/completions', { model: 'gpt-3.5-turbo', messages: [{ role: 'user', content: req.body.message }], temperature: 0.7 }, { headers: { 'Authorization': `Bearer ${process.env.OPENAI_API_KEY}`, 'Content-Type': 'application/json' } }); res.json(response.data); });Testing the Endpoint:
Use a tool like Postman to send a
POSTrequest tohttp://localhost:5000/chat.
Last updated