DEV Community

Cover image for Full-Stack React & Node.js - Get data from server
Dave
Dave

Posted on

4 2

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

Qodo Takeover

Introducing Qodo Gen 1.0: Transform Your Workflow with Agentic AI

While many AI coding tools operate as simple command-response systems, Qodo Gen 1.0 represents the next generation: autonomous, multi-step problem-solving agents that work alongside you.

Read full post

Top comments (1)

Collapse
 
angelidito profile image
Angel Mori M. D.

I guess when you say "Finally, change app.js to this", you actually are talking about node-server's index.js.

AWS Security LIVE!

Join us for AWS Security LIVE!

Discover the future of cloud security. Tune in live for trends, tips, and solutions from AWS and AWS Partners.

Learn More

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay