When I try to run this code on browser it display buttons but when I click on the button “WebSocketClient.js:13 WebSocket connection to ‘ws://localhost:3000/ws’ failed: ” error throws. My server file has following code
const express = require('express');
const { Pool } = require('pg');
const app = express();
const port = 3000;
app.use(express.json());
const pool = new Pool({
user: 'user',
host: 'db',
database: 'mydatabase',
password: 'password',
port: 5432,
});
app.get('/api/hello', (req, res) => {
res.json({ message: 'Hello World' });
});
app.get('/api/hello/french', (req, res) => {
res.json({ message: 'Bonjour le monde' });
});
app.post('/api/user', async (req, res) => {
const { name } = req.body;
const client = await pool.connect();
try {
await client.query('INSERT INTO users (name) VALUES ($1)', [name]);
res.status(201).send('Name saved');
} finally {
client.release();
}
});
app.listen(port, () => {
console.log(`Server is running on http://localhost:${port}`);
});
my app.js has following code
import React, { useState } from 'react';
import axios from 'axios';
function App() {
const [message, setMessage] = useState('');
const [name, setName] = useState('');
const handleEnglishClick = async () => {
try {
console.log('Fetching English message...');
const response = await axios.get('http://localhost:3000/api/hello');
console.log('Response:', response);
setMessage(response.data.message);
} catch (error) {
console.error('Error fetching English message:', error);
}
};
const handleFrenchClick = async () => {
try {
console.log('Fetching French message...');
const response = await axios.get('http://localhost:3000/api/hello/french');
console.log('Response:', response);
setMessage(response.data.message);
} catch (error) {
console.error('Error fetching French message:', error);
}
};
const handleSubmit = async (event) => {
event.preventDefault();
try {
console.log('Saving name...');
await axios.post('http://localhost:3000/api/user', { name });
alert('Name saved');
} catch (error) {
console.error('Error saving name:', error);
}
};
return (
<div>
<h1>{message}</h1>
<h2>this is output panel</h2>
<button onClick={handleEnglishClick}>English</button>
<button onClick={handleFrenchClick}>French</button>
<form onSubmit={handleSubmit}>
<input
type="text"
value={name}
onChange={(e) => setName(e.target.value)}
placeholder="Enter your name"
/>
<button type="submit">Save Name</button>
</form>
</div>
);
}
export default App;
my dockerfile has folowing code
version: '3.8'
services:
db:
image: postgres:latest
restart: always
environment:
POSTGRES_USER: user
POSTGRES_PASSWORD: password
POSTGRES_DB: mydatabase
ports:
- "5432:5432"
networks:
- mynetwork
web:
build: .
ports:
- "3000:3000"
depends_on:
- db
networks:
- mynetwork
client:
build:
context: ./client
ports:
- "3001:3000"
depends_on:
- web
environment:
- REACT_APP_API_URL=http://web:3000/api
networks:
- mynetwork
networks:
mynetwork:
Please help me in this issue.