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

neohed

Dave

Posted on June 27, 2022

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

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
}
Enter fullscreen mode Exit fullscreen mode

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;
Enter fullscreen mode Exit fullscreen mode

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}/`);
});
Enter fullscreen mode Exit fullscreen mode

Now run your Node.js server with this command:

npm run start
Enter fullscreen mode Exit fullscreen mode

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: ""
  }
}
Enter fullscreen mode Exit fullscreen mode

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

Code repo: Github Repository

💖 💪 🙅 🚩
neohed
Dave

Posted on June 27, 2022

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related