This site runs best with JavaScript enabled.

Full-Stack React & Node.js, Part 4 - Get data from server

June 27, 2022


Simply Learn Full-Stack React & Node.js

Inside folder node-server, create a new folder called "controllers." Inside add a file called note.controller.js and add the following code:

1const note = {
2 id: 1,
3 title: 'A Note',
4 content: 'Lorem ipsum dolor sit amet',
5 author: 'neohed',
6 lang: 'en',
7 isLive: true,
8 category: '',
9}
10
11async function getNote(req, res) {
12 res.json({ note });
13}
14
15module.exports = {
16 getNote
17}

Why .controller.js? In a complex app, you will have many entities and associated route, controller, middleware and data files. Tagging each file with .controller, .route, .middleware, .data, etc., makes it much less confusing when you have many files open in your editor.

Next, inside folder node-server, create another folder called "routes." Inside add a file called index.js and add the following code:

1const express = require('express');
2const noteRouter = express.Router();
3const noteController = require('../controllers/note.controller');
4
5noteRouter.get('', noteController.getNote);
6
7const routes = app => {
8 app.use('/note', noteRouter);
9};
10
11module.exports = routes;

Finally, change app.js to this:

1const express = require('express');
2const cors = require('cors');
3const morganLogger = require('morgan');
4const bodyParser = require('body-parser');
5const initRoutes = require('./routes/index');
6
7const env = process.env.NODE_ENV || 'development';
8const app = express();
9
10if (env === 'development') {
11 app.use(cors());
12}
13
14app.use(morganLogger('dev'));
15app.use(bodyParser.json());
16app.use(bodyParser.urlencoded({extended: true}));
17
18initRoutes(app);
19
20app.use(function (req, res, next) {
21 const error = 'Here be dragons. Route not found';
22 console.info(`404 error! ${error}`)
23 res.status(404).send(error);
24});
25
26const port = 4011;
27
28app.listen({port}, async () => {
29 const baseUrl = `http://localhost:${port}`;
30
31 console.log(`Server running at: \t @ ${baseUrl}/`);
32});

Now run your Node.js server with this command:

npm run start

When the console outputs a message saying the server is running, paste this URL into a browser: "http://localhost:4011/note" and you should see the following object displayed:

1{
2 note: {
3 id: 1,
4 title: "A Note",
5 content: "Lorem ipsum dolor sit amet",
6 author: "neohed",
7 lang: "en",
8 isLive: true,
9 category: ""
10 }
11}

You now have a working client and server. Next we will finally get the client and server to communicate, ...

Code repo: Github Repository

Share article



neohed © 2022