I looked at quite a few examples of how people use react js with node express, it all comes down to the fact that I need to run the request handler server on one port and the client server through npm start on another port. I don’t understand if you can somehow keep everything on one port and how it will look like on the release.

    1 answer 1

    This is done so that the front and the beck development do not depend on each other and run in parallel. There is one server that returns static files and does nothing else. And there is a second server in which the logic of working with data is registered.

    On the front, ajax requests can be blocked while the API is not ready, and the back is not a gentle front for developers.

    The most primitive example is all on one server.

    api.js

    The logic of working with data

    const express = require('express'); // некая база данных const db = require('./db'); const router = express.Router(); // что-то делаем router.post('/users/:id', async (req, res) => { try { const id = req.params.id; const user = await db.fetchUserById(id); res.status(200).json(user); } catch (e) { res.sendStatus(500); } }); module.exports = router; 

    index.js

     const path = require('path'); const express = require('express'); const bodyParser = require('body-parser'); // Наше API const api = require('./api'); const PORT = process.env.PORT; const indexHTML = path.resolve(__dirname,'../public/index.html'); const app = express(); app.use(bodyParser.json()); // Для статических файлов app.use('/', express.static('public')); // Подключаем API // Теперь мы можем делать ajax запросы // и получить пользователя с id 1 по урлу /api/users/1 app.use('/api', api); app.get('/*', (req, res) => res.sendFile(indexHTML)); app.listen(PORT, () => console.info('Server is running on port:', PORT));