return ( <div> <h1>Microservices User Management</h1> <form onSubmit={createUser}> <input placeholder="Name" value={name} onChange={(e) => setName(e.target.value)} /> <input placeholder="Email" value={email} onChange={(e) => setEmail(e.target.value)} /> <button type="submit">Add User</button> </form> <ul> {users.map(user => ( <li key={user._id}>{user.name} - {user.email}</li> ))} </ul> </div> ); }
version: '3.8' services: user-service: build: ./services/user-service ports: - "4001:4001" environment: - MONGO_URI=mongodb://mongo-users:27017/usersdb depends_on: - mongo-users mongo-users: image: mongo ports: - "27017:27017"
api-gateway: build: ./api-gateway ports: - "5000:5000" depends_on: - user-service - product-service
import React, { useState, useEffect } from 'react'; import axios from 'axios'; const API_GATEWAY = 'http://localhost:5000'; microservices with node js and react download
npm install express http-proxy-middleware
app.listen(5000, () => { console.log('API Gateway running on port 5000'); });
app.use('/orders', createProxyMiddleware({ target: 'http://localhost:4003', changeOrigin: true, })); // Publish event await publisher
Introduction In modern web development, the microservices architecture has become a go-to approach for building scalable, maintainable, and resilient applications. When combined with Node.js for the backend and React for the frontend, you get a powerful, full-stack JavaScript solution.
const express = require('express'); const { createProxyMiddleware } = require('http-proxy-middleware'); const app = express();
const createUser = async (e) => { e.preventDefault(); await axios.post( ${API_GATEWAY}/users , { name, email }); fetchUsers(); setName(''); setEmail(''); }; // Publish event await publisher.publish('user-created'
MONGO_URI=mongodb://localhost:27017/usersdb PORT=4001 Run the service: node server.js The API Gateway routes incoming requests from the React frontend to the appropriate microservice.
// Publish event await publisher.publish('user-created', JSON.stringify(newUser));
// User Schema const userSchema = new mongoose.Schema({ name: String, email: String, createdAt: { type: Date, default: Date.now }, });