async-labs / builderbook

Open source web application to learn JS stack: React, Material-UI, Next.js, Node.js, Express.js, Mongoose, MongoDB database.
https://builderbook.org
MIT License
3.77k stars 893 forks source link

Chapter 3 #444

Closed abeebridwan closed 3 years ago

abeebridwan commented 3 years ago

-------Testing withAuth-------------

This isn't working - user is passed to withAuth HOC on the serve not index.js page on the client right?

server.get('/', async (req, res) => { const user = await User.findOne({ slug: 'team-builder-book' }); app.render(req, res, '/', { user }); });

---------this below is working: -------------------- server.get('/', (req, res) => { User.findOne({ slug: 'team-builder-book' }).then((user) => { req.user = user; app.render(req, res, '/'); }); });

Please change it

tima101 commented 3 years ago

@olumide025 Method User.findOne returns Promise. async/await is just syntactic sugar for Promise.then. Check up this section:

https://builderbook.org/books/builder-book/authentication-hoc-getinitialprops-method-login-page-and-nprogress-asynchronous-execution-promise-then-async-await-google-oauth-api-infrastructure-setupgoogle-verify-passport-strategy-express-routes-auth-google-oauth2callback-logout-generateslug-this-set-up-at-google-cloud-platform#asynchronous-execution-and-callback

Please make sure that your database is connected to your server and that database contains User MongoDB document with slug: 'team-builder-book'.

tima101 commented 3 years ago

@olumide025 I ran code and you are right about

req.user = user;

Because inside withAuth:

const user = ctx.req ? ctx.req.user && ctx.req.user.toObject() : globalUser;

Since on the server, I called app.render like this:

app.render(req, res, '/', { user });

I meant to define user inside withAuth HOC using ctx.query instead of ctx.req.user:

const user = ctx.query ? ctx.query.user && ctx.query.user.toObject() : globalUser;

In Chapter 2, indeed, I defined page's user as ctx.query.user. However, in Chapter 3, I am gonna fix Express route by using req.user = user like you suggested. Thank you so much!


Made changes to content and codebase.