Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

Sorry, you do not have permission to ask a question, You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please type your username.

Please type your E-Mail.

Please choose an appropriate title for the post.

Please choose the appropriate section so your post can be easily searched.

Please choose suitable Keywords Ex: post, video.

Browse

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

Querify Question Shop: Explore Expert Solutions and Unique Q&A Merchandise

Querify Question Shop: Explore Expert Solutions and Unique Q&A Merchandise Logo Querify Question Shop: Explore Expert Solutions and Unique Q&A Merchandise Logo

Querify Question Shop: Explore Expert Solutions and Unique Q&A Merchandise Navigation

  • Home
  • About Us
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • About Us
  • Contact Us
Home/ Questions/Q 6250

Querify Question Shop: Explore Expert Solutions and Unique Q&A Merchandise Latest Questions

Author
  • 60k
Author
Asked: November 27, 20242024-11-27T04:48:08+00:00 2024-11-27T04:48:08+00:00

Full-Stack React & Node.js – Create the server

  • 60k

First create a folder node-server at the same level as folder react-client

Inside the node-server folder, use a shell/CLI to enter this command to create a package.json file:

npm init -y 
Enter fullscreen mode Exit fullscreen mode

The -y flag means that package.json will be filled with defaults. You can edit the file later to add your name and repository details, etc.

Next run this to install some dependencies:

npm i -S express body-parser cors morgan 
Enter fullscreen mode Exit fullscreen mode

i is shorthand for install
-S is shorthand for -save

Create index.js and paste in this code:

const express = require('express'); const cors = require('cors'); const morganLogger = require('morgan'); const bodyParser = require('body-parser');  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}));  // 404 route not found! 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: 	 @ ${baseUrl}/`); }); 
Enter fullscreen mode Exit fullscreen mode

I will briefly explain the packages we are importing.

express is the web framework.

The cors package disables “cross origin resource sharing”, where origin is a URL and resources are assets like images. The purpose of the cors policy is to prevent a website from pointing their image links to a different site and stealing hosting costs. In development we allow cors because we run both the React client and the Node server on one machine, each in their own process (live you could deploy both to the same folder and avoid cors issues). The port numbers on the server and client URL's are needed so the traffic (HTTP requests and responses) can be sent to the correct process. Port numbers are included in the browser decision on the origin of the server response

Your browser sees the website is on port 3000 but it attempts to fetch data from port 4011. Even though they both run on localhost, because the port numbers are different, to a browser they are different websites entirely! If we didn't disable cors, this request would violate the same-origin policy and be denied!

body-parser is middleware that parses incoming requests to extract data for us, in this case json (it also includes a few other parsers that can be useful).

morgan is a middleware request logger. In this case we pipe all messages to the console (you could instead write to a file). This is one of the most essential things to include in any node server. For troubleshooting and debugging, seeing all requests logged to your console is pure gold!

You might notice our server returns no data, has no routes defined, but has a 404 handler. I always add a 404 handler first! When your app grows and has complex routing, getting a clear message, a “final destination” for unmatched routes is essential for development and debugging.

Next edit package.json, and change the “scripts” section to add an additional line:

  "scripts": {     "start": "node index.js",     "test": "echo "Error: no test specified" && exit 1"   }, 
Enter fullscreen mode Exit fullscreen mode

Finally you should be able to run your Node.js server with this command:

npm run start 
Enter fullscreen mode Exit fullscreen mode

Run this in the same folder as the package.json file

When the console outputs a message saying the server is running, paste this URL into a browser: “http://localhost:4011/“

You should see a text message: “Here be dragons. Route not found”

This is good. We received an HTTP 404 error, which is what we expect as, currently, our server returns no data and has no routing paths defined.

You now have a working client and server. Next we will return some data.

Code repo: Github Repository

javascriptnodereactwebdev
  • 0 0 Answers
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

Sidebar

Ask A Question

Stats

  • Questions 4k
  • Answers 0
  • Best Answers 0
  • Users 2k
  • Popular
  • Answers
  • Author

    ES6 - A beginners guide - Template Literals

    • 0 Answers
  • Author

    Understanding Higher Order Functions in JavaScript.

    • 0 Answers
  • Author

    Build a custom video chat app with Daily and Vue.js

    • 0 Answers

Top Members

Samantha Carter

Samantha Carter

  • 0 Questions
  • 20 Points
Begginer
Ella Lewis

Ella Lewis

  • 0 Questions
  • 20 Points
Begginer
Isaac Anderson

Isaac Anderson

  • 0 Questions
  • 20 Points
Begginer

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help

Footer

Querify Question Shop: Explore Expert Solutions and Unique Q&A Merchandise

Querify Question Shop: Explore, ask, and connect. Join our vibrant Q&A community today!

About Us

  • About Us
  • Contact Us
  • All Users

Legal Stuff

  • Terms of Use
  • Privacy Policy
  • Cookie Policy

Help

  • Knowledge Base
  • Support

Follow

© 2022 Querify Question. All Rights Reserved

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.