GithubHelp home page GithubHelp logo

packtpublishing / full-stack-react-projects-second-edition Goto Github PK

View Code? Open in Web Editor NEW
447.0 16.0 541.0 14.27 MB

Full-Stack React Projects - Second Edition, published by Packt

License: MIT License

JavaScript 99.86% HTML 0.14%

full-stack-react-projects-second-edition's Introduction

Full Stack React Projects - Second Edition

Full-Stack React Projects - Second Edition

This is the code repository for Full-Stack React Projects - Second Edition, published by Packt.

Learn MERN stack development by building modern web apps using MongoDB, Express, React, and Node.js

What is this book about?

Facebook's React combined with industry-tested, server-side technologies, such as Node, Express, and MongoDB, enables you to develop and deploy robust real-world full-stack web apps. This updated second edition focuses on the latest versions and conventions of the technologies in this stack, along with their key features such as Hooks in React and async/await in JavaScript. The book also explores advanced topics such as implementing real-time bidding, a web-based classroom app, and data visualization in an expense tracking app.

This book covers the following exciting features:

  • Extend any MERN-based application to build a variety of applications
  • Add real-time communication capabilities with Socket.IO
  • Implement data visualization features for React applications using Victory
  • Develop media streaming applications using MongoDB GridFS
  • Improve SEO for your MERN apps by implementing server-side rendering with data

If you feel this book is for you, get your copy today!

https://www.packtpub.com/

Instructions and Navigations

All of the code is organized into folders. For example, Chapter02.

The code will look like the following:

if (test expression)
{
  Statement upon condition is true
}

Following is what you need for this book: This is one of the most useful web development books for JavaScript developers who may have worked with React but have minimal experience in full-stack development with Node, Express, and MongoDB.

With the following software and hardware list you can run all code files present in the book (Chapter 1-15).

Software and Hardware List

Chapter Software required OS required
1 Node.js(13.12.0)with npm(6.14.4) Supports multiple OS
2 Yarn(1.22.4) Supports multiple OS
3 MongoDB (Community Server 4.2.5) Supports multiple OS
4 Chrome Browser (latest) Supports multiple OS
5 Git (latest) Supports multiple OS
6 Visual Studio Code (latest) Supports multiple OS
7 ARC (latest) Supports multiple OS

Related products

Get to Know the Author

Shama Hoque has more than 9 years of experience as a software developer and mentor, with a master’s in software engineering from Carnegie Mellon University. From Java programming to full-stack development with JavaScript, the applications she has worked on include national Olympiad registration websites, universally accessible widgets, video conferencing apps, and medical 3D reconstruction software. Currently, she makes web-based prototypes for R&D start-ups in California, while training aspiring software engineers and teaching web development to CS undergrads in Bangladesh.

Other books by the author

Suggestions and Feedback

Click here if you have any feedback or suggestions.

full-stack-react-projects-second-edition's People

Contributors

deepesh-packt avatar packt-itservice avatar shamahoque avatar techsachinkumar avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

full-stack-react-projects-second-edition's Issues

Issue in the server.js file mongoose.connect code

The options are not supported on mongoose v6, however, it's the useCreateIndex that was completely crashing a mirror of the repo's code. Wirth updating as came close to abandoning the book as 'outdated' at such an early section (chapter 3)

chapter-03- express-jwt

Hello,
It seems that this code broke at "express-jwt": "^7.7.0"

How could I modify this code to work on the the latest version

const requireSignin = expressJwt({
secret: config.jwtSecret,
userProperty: 'auth'
})

got the following error:

const requireSignin = express_jwt__WEBPACK_IMPORTED_MODULE_2___default()({
^

TypeError: express_jwt__WEBPACK_IMPORTED_MODULE_2___default(...) is not a function
at eval (webpack://user_backend/./server/controllers/auth.controller.js?:69:73)
at Object../server/controllers/auth.controller.js (/Users/natu/qingning_website/user_backend/dist/server.generated.js:29:1)
at webpack_require (/Users/natu/qingning_website/user_backend/dist/server.generated.js:243:41)
at eval (webpack://user_backend/./server/routes/user.routes.js?:8:86)
at Object../server/routes/user.routes.js (/Users/natu/qingning_website/user_backend/dist/server.generated.js:79:1)
at webpack_require (/Users/natu/qingning_website/user_backend/dist/server.generated.js:243:41)
at eval (webpack://user_backend/./server/express.js?:20:77)
at Object../server/express.js (/Users/natu/qingning_website/user_backend/dist/server.generated.js:49:1)
at webpack_require (/Users/natu/qingning_website/user_backend/dist/server.generated.js:243:41)
at eval (webpack://user_backend/./server/server.js?:3:66)

Error Creating New User

Hi. In the Checking The Standalone Backend Part, I got an error "404 not found" when trying to send post request to /api/users route using Chrome ARC.
Capture

Helmet & webpack-dev-Middleware

At this time, I am trying this codes, helmet is forcing https instead of http and webpack-dev-Middleware was not writing the bundle.js file under /dist, due to missing argument, writeToDisk: true, by default its false.

Separating client and server repos to serve in individual docker containers

I am learning how to configure docker containers and am trying to reconfigure the current project structure to include two separate package.json one for each client and server folder. Im running into trouble when trying to compile each separately.

How should I modify the structure to be able to successfully run client and server individually? (specifically mern marketplace)

Jest test example from Chapter 15 does not work

Hi, unfortunately unit test example from chapter 15 (section Adding the test) does not work. This is the error:
TypeError: Cannot read property 'mockReturnValue' of undefined

  1. How is importing auth from auth-helper expected to work if mocked authorization object is also defined as const auth:
    import auth from './../auth/auth-helper.js' and const auth = dummyAuthObject. Doesnt this make two variables called auth?

  2. Why isnt onRemove function passed as a prop when it is required in Post component?

Follow/Unfollow API is not working - giving a 400-bad request error

Hi,
In mern social, when I clicked on the follow button, it gives error of 400 (Bad Request).
while debugging, I found that userById method gives ERROR - USER NOT FOUND in the clickFollowButton method (Profile.js). But getUser method is working fine in useEffect.

user-routes.js

router.param("userId", getUserById);

router.get("/users", getAllUsers);
router.post("/users", createUser);

router.get("/users/:userId", isSignedIn, getUser);
router.put("/users/:userId", isSignedIn, hasAuthorization, updateUser);
router.delete("/users/:userId", isSignedIn, hasAuthorization, deleteUser);

router.get("/users/photo/:userId", photo);
router.get("/users/defaultphoto", defaultPhoto);

router.put("/users/follow", isSignedIn, addFollowing, addFollower);
router.put("/users/unfollow", isSignedIn, removeFollowing, removeFollower);

clickFollowButton

const clickFollowButton = (callApi) => {
    const { user, token } = isAuthenticated();
    callApi(
      {
        userId: user._id,
      },
      {
        token: token,
      },
      values.user._id
    ).then((data) => {
      if (data?.error) {
        setValues({ ...values, error: data.error });
        console.log("click follow button", data.error);
        //GIVES ERROR - USER NOT FOUND
      } else {
        setValues({ ...values, user: data, following: !values.following });
        console.log("click follow button", data);
      }
    });
  };

api-user.js

export const follow = (userId, token, followId) => {
  return fetch(`${API}/api/users/follow/`, {
    method: "PUT",
    headers: {
      Accept: "application/json",
      "Content-Type": "application/json",
      Authorization: `Bearer ${token}`,
    },
    body: JSON.stringify({ userId: userId, followId: followId }),
  })
    .then((response) => {
      return response.json();
    })
    .catch((err) => console.log("FOLLOW FAILED", err));
};

export const unfollow = (userId, token, unfollowId) => {
  return fetch(`${API}/api/users/unfollow/`, {
    method: "PUT",
    headers: {
      Accept: "application/json",
      "Content-Type": "application/json",
      Authorization: `Bearer ${token}`,
    },
    body: JSON.stringify({ userId: userId, unfollowId: unfollowId }),
  })
    .then((response) => {
      return response.json();
    })
    .catch((err) => console.log(err));
};

addFollowing & addFollower

exports.addFollowing = (req, res, next) => {
  User.findByIdAndUpdate(
    req.body.userId,
    { $push: { following: req.body.followId } },
    (err, result) => {
      if (err) {
        return res.status(400).json({
          error: "Unable to add following",
        });
      }
      next();
    }
  );
};

exports.addFollower = (req, res) => {
  User.findByIdAndUpdate(
    req.body.followId,
    { $push: { followers: req.body.userId } },
    { new: true }
  )
    .populate("following", "_id name")
    .populate("followers", "_id name")
    .exec((err, result) => {
      if (err) {
        return res.status(400).json({
          error: "Unable to add following",
        });
      }
      result.hashed_password = undefined;
      result.salt = undefined;
      res.json(result);
    });
};

ERROR in multi ./server/server.js

Hi, I'm test the Chapter 3 - but it apperar this error when I test the server:

mz2@mz2:~/jwtapp$ yarn development yarn run v1.22.4 $ nodemon [nodemon] 2.0.3 [nodemon] to restart at any time, enterrs[nodemon] watching path(s): server [nodemon] watching extensions: js,mjs,json [nodemon] startingwebpack --mode=development --config webpack.config.server.js && node ./dist/server.generated.js`
Hash: 1e73917036ff8f9ada48
Version: webpack 4.43.0
Time: 33ms
Built at: 05/11/2020 9:15:56 PM
Asset Size Chunks Chunk Names
server.generated.js 3.98 KiB main [emitted] main
Entrypoint main = server.generated.js
[0] multi ./server/server.js 28 bytes {main} [built]

ERROR in multi ./server/server.js
Module not found: Error: Can't resolve '/home/mz2/jwtapp/server/server.js' in '/home/mz2/jwtapp'
@ multi ./server/server.js main[0]
[nodemon] process failed, unhandled exit code (2)
[nodemon]
[nodemon] Either the command has a syntax error,
[nodemon] or it is exiting with reserved code 2.
[nodemon]
[nodemon] To keep nodemon running even after a code 2,
[nodemon] add this to the end of your command: || exit 1
[nodemon]
[nodemon] Read more here: https://git.io/fNOAG
[nodemon]
[nodemon] nodemon will stop now so that you can fix the command.
[nodemon]
[nodemon] Error
at Bus. (/home/mz2/jwtapp/node_modules/nodemon/lib/nodemon.js:156:25)
at Bus.emit (events.js:323:22)
at ChildProcess. (/home/mz2/jwtapp/node_modules/nodemon/lib/monitor/run.js:187:11)
at ChildProcess.emit (events.js:311:20)
at Process.ChildProcess._handle.onexit (internal/child_process.js:275:12)
Done in 0.44s.

`
How to fix this error?

Private Route

I have a problem withe the PrivateRouter component.
When I try to insert directly the path in the browser (for example: localhost:3000/posts) it redirects to Signin even if I am already logged in.

supported options connect mongoose

According to the documentation useNewUrlParser, useUnifiedTopology, useFindAndModify, and useCreateIndex are no longer supported. Mongoose 6 always behaves as if useNewUrlParser, useUnifiedTopology and useCreateIndex are true, and useFindAndModify is false. So it asks us to remove these options from our code. When trying to connect to the DB, but precisely with useCreateIndex our code will not work.

How to deploy?

As I know the codebase has one package.json file for both client-side a server-side. So how to deploy it.

expressJWT - algorithms should be set

When I got to the 'Checking the standalone backend' section, I ran npm run development and received the following error:

Error: algorithms should be set at module.exports (D:\react\mern-skeleton\node_modules\express-jwt\lib\index.js:22:34) at eval (webpack:///./server/controllers/auth.controller.js?:56:73)

After googling, I found a suggestion for adding algorithms: ['RS256'] to the requireSignin declaration and it solved the error.

const requireSignin = expressJwt({ secret: config.jwtSecret, userProperty: 'auth', algorithms: ['RS256'], });

I don't know that RS256 is the correct algorithm. I was wondering if I failed to include something from the example.

Cannot get /url in React App with Webpack

`

    <BrowserRouter>
    <Header />
        <Switch>
        <Route exact path="/" component={Home} />
          <Route exact path="/products" component={Products} />
          <Route exact path="/contact" component={Contact} />
          <Route path="/services" component={Services} />
          <Route component={Nomatch} />
        </Switch>
    </BrowserRouter>

`
I have created a NavBar with the components Products, Contact, Services
I am able to access the Products page when clicked on the Navbar but when I explicitly type localhost:3000/products , I get the error message Cannot get/products
Please help me resolve this issue

Unable to run the client and the server (Chapter 8)

Hello, I downloaded the code for chapter 8 and made some minor modifications. However, when I run yarn development, I can only run the server (on port 5000) and the client (on port 3000).

here is what I am getting on the console.
Screen Shot 2021-06-02 at 17 12 56

Screen Shot 2021-06-02 at 17 13 07

The server is working fine as I can test the API but when I open localhost:3000 in my browser I am not getting anything as can be seen below:

Screen Shot 2021-06-02 at 17 16 27

Any advice will be helpful

How to Deploy

Could you show or explain how to deploy these apps ? I did a project with like exactly your folder tree and SSR but i do not know how to deploy this kind of app. Can you help me about that , please ? I tried heroku and netlify but i got errors like no index.html file found or favicon.ico not found or unvalid method.

Problem on the client side

The render of react does not work, when I enter the section "Running and opening in the browser" (Adding a React Frontend to Complete MERN), when entering the command "yarn development".

I have all the code you wrote up to that chapter, the backend works fine. In the client it does not render the main.js template of react (cannot GET/)
Here I leave the link to the repository of the code that I have, it is the same as the one in the indicated section (https://github.com/esteban-master/esqueleto_MERN)

The course of the book is great, I can not continue reading ... I hope your help. Thank you very much!

Error: Module build failed... server/express.js: Unexpected token (52:10)

Appear this error when lauch the command:

yarn start or yarn development

Error: Module build failed (from ./node_modules/babel-loader/lib/index.js):
SyntaxError: /home/mz2/teste/server/express.js: Unexpected token (52:10)

const markup = ReactDOMServer.renderToString( sheets.collect( <StaticRouter location={req.url} context={context}> ^ <ThemeProvider theme={theme}> <MainRouter /> </ThemeProvider>

webpack should resolve .jsx files

To be friendly with IDE, such as IntelliJ in my case, react files should be renamed to .jsx and webpack should resolve .js and .jsx extensions.

const config = {
  module: {
    rules: [
      {
        test: /\.jsx?$/,
        exclude: /node_modules/,
        use: ['babel-loader'],
        resolve: {
          extensions: ['.js', '.jsx']
        }
      }
    ]
  }
}

or

const config = {
  resolve: {
    extensions: ['.js', '.jsx']
  }
}

After using server-side rendering, I always got warning in console

After using server-side rendering, I always got warning, something like:
"
react-dom.development.js?61bb:67 Warning: Text content did not match. Server: "Sign up" Client: "My Shops"
"
I am not quite sure where's this problem come from. But I suppose it comes from the detail of server-side rendering.

Comments and likes section do not get updated after adding a new post (MERN Social, chapter05)

Hi, I have found an issue that is a bug. Short description:

GIVEN: User is logged AND Home page is opened AND There are older posts visible with comments and likes (e.g 1 like and 1 comment for the latest post)
WHEN: User adds new post
THEN: New post should not have any likes nor comments

New post is displayed on top of the previous comments and likes

Video available on request.

package.json script on Windows

I didn't test the script "start": "NODE_ENV=production node ./dist/server.generated.js" on Linux or Mac. But script on Windows should be "start": "SET NODE_ENV=production && node ./dist/server.generated.js"

Routing in client

I have configured the express app to send the template HTML when the root is accessed

app.get('/', (req, res) => { res.status(200).send(template()); })
However, when I try to access routes such as '/users', '/profile' it goes to the backend and I get the error 'cannot GET/users' because this isn't a backend route.

In the first few chapters of the book, while building the social media app this is how it was indicated to go about it. Why isn't the router working with the given information in the book.
Currently I cannot render the specific pages by directly entering the URL or reloading. I have to go to the root and click a linked button

Unable to Run Chap3 Skeleton

Hello. I am a complete novice in Node so please excuse the naive question. I have been coding along in Chapter 3 and can not get my build to run.

I get the following error when running yarn development. It looks like babel is not changing my template.js file back into normal JS but I have no idea how to fix that.

(node:178205) Warning: To load an ES module, set "type": "module" in the package.json or use the .mjs extension.
/home/matt/Desktop/programmingProjects/mernBackend-template/template.js:1
export default () => {
^^^^^^

SyntaxError: Unexpected token 'export'

I am sure I am missing something simple but just cannot figure it out. All of my code is pushed up to https://github.com/matton2/mernBackend-template for reference.

Thank you in advance!

Webpack Eval() error

When trying to run the project, I continuously run into this issue in the console.

Uncaught EvalError: Refused to evaluate a string as JavaScript because 'unsafe-eval' is not an allowed source of script in the following Content Security Policy directive: "script-src 'self'".

at Object../node_modules/webpack-hot-middleware/client.js?reload=true (bundle.js:2968)
at __webpack_require__ (bundle.js:3029)
at bundle.js:4098
at bundle.js:4101

Is there a solution? This seems to be a common webpack issue that I can't figure out.

Rendering a home page view

Hi!, I have a problem when I try to Rendering the home page view. The problem occurs when i go to localhost:3000, I only see blank page and components are not rendered :(. When i start the server all its ok, but i don't understand why happend this. I checked that my code is the same that the code in github. If you need more information to help me I am attentive to your comments. Thx!

image

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.