Full-Stack React & Node.js - Get data from server
Dave
Posted on June 27, 2022
Inside folder node-server, create a new folder called "controllers." Inside add a file called note.controller.js and add the following code:
const note = {
id: 1,
title: 'A Note',
content: 'Lorem ipsum dolor sit amet',
author: 'neohed',
lang: 'en',
isLive: true,
category: '',
}
async function getNote(req, res) {
res.json({ note });
}
module.exports = {
getNote
}
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:
const express = require('express');
const noteRouter = express.Router();
const noteController = require('../controllers/note.controller');
noteRouter.get('', noteController.getNote);
const routes = app => {
app.use('/note', noteRouter);
};
module.exports = routes;
Finally, change app.js to this:
const express = require('express');
const cors = require('cors');
const morganLogger = require('morgan');
const bodyParser = require('body-parser');
const initRoutes = require('./routes/index');
const env = process.env.NODE_ENV || 'development';
const app = express();
if (env === 'development') {
app.use(cors());
}
app.use(morganLogger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: true}));
initRoutes(app);
app.use(function (req, res, next) {
const error = 'Here be dragons. Route not found';
console.info(`404 error! ${error}`)
res.status(404).send(error);
});
const port = 4011;
app.listen({port}, async () => {
const baseUrl = `http://localhost:${port}`;
console.log(`Server running at: \t @ ${baseUrl}/`);
});
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:
{
note: {
id: 1,
title: "A Note",
content: "Lorem ipsum dolor sit amet",
author: "neohed",
lang: "en",
isLive: true,
category: ""
}
}
You now have a working client and server. Next, we will finally get the client and server to communicate...
Code repo: Github Repository
Posted on June 27, 2022
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.