# 3. Introduction to Web Backend Using JavaScript

### Setting Up a Simple Node.js Server

1. **Initialize a Node.js Project**:

   ```bash
   npm init -y
   ```
2. **Install Express**:

   ```bash
   npm install express
   ```
3. **Create a Simple Server**:

   * Create `server.js`:

   ```javascript
   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:

   ```bash
   node server.js
   ```

**Connecting Backend with GenAI API**

1. **Install Axios**:

   ```bash
   npm install axios
   ```
2. **Create an Endpoint to Call GenAI**:

   * Update `server.js`:

   ```javascript
   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);
   });
   ```
3. **Testing the Endpoint**:
   * Use a tool like Postman to send a `POST` request to `http://localhost:5000/chat`.
