Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
609 views
in Technique[技术] by (71.8m points)

node.js - How to set cookies express, react.js

I am building a login system using express for node.js and react.js. In my back-end when a user logs in, it creates a cookie. When I go to Network > Login I can see this:

Set-Cookie: user_id=s%3A1.E%2FWVGXrIgyXaM4crLOoxO%2Fur0tdjeN6ldABcYOgpOPk; Path=/; HttpOnly; Secure

But when I go to Application > Cookies > http://localhost:3000, there is nothing there. I believe that is because I am not allowing credentials to go through correctly when I do a post request from the client side. How do I go about this? Please, let me know if I can improve my question in any way.

            //Login back-end
            router.post('/login', (req, res, next) => {
                if(validUser(req.body)) {
                    User
                        .getOneByEmail(req.body.email)
                        .then(user => {
                            if(user) {
                                bcrypt
                                    .compare(req.body.password_digest, user.password_digest)
                                    .then((result) => {
                                        if(result) {
                                            const isSecure = process.env.NODE_ENV != 'development';

                                            res.cookie('user_id', user.id, {
                                                httpOnly: true,
                                                secure: isSecure,
                                                signed: true
                                            })
                                            res.json({
                                                message: 'Logged in'
                                            });
                                        } else {
                                            next(new Error('Invalid Login'))
                                        }
                                    });
                            } else {
                                next(new Error('Invalid Login'))
                            }
                        });
                } else {
                    next(new Error('Invalid Login'))
                }
            });

            //Allow CORS index.js
            app.use(
            cors({
                origin: "http://localhost:3000",
                credentials: true
            })
            );

            //Login client side (React.js)
            loginUser(e, loginEmail, password) {
            e.preventDefault();

            let email = loginEmail;
            let password_digest = password;
            let body = JSON.stringify({ email, password_digest });

            fetch("http://localhost:5656/api/login", {
                method: "POST",
                headers: {
                "Content-Type": "application/json"
                },
                credentials: "include",
                body
            })
                .then(response => response.json())
                .then(user => {
                console.log(user);
                });
            }
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You should be secure of set "credentials" in the server and in app.

Try to set on you index.js or app.js server side this:

  app.use(function(req, res, next) {
  res.header('Content-Type', 'application/json;charset=UTF-8')
  res.header('Access-Control-Allow-Credentials', true)
  res.header(
    'Access-Control-Allow-Headers',
    'Origin, X-Requested-With, Content-Type, Accept'
  )
  next()
})

and in you client site add options like this:

let axiosConfig = {
  withCredentials: true,
}

export async function loginUser(data) {
  try {
    const res = await axios.post(
      `${URL}:${PORT}/${API}/signin`,
      data,
      axiosConfig
    )
    return res
  } catch (error) {
    console.log(error)
  }
}

Edit

To set "credentials" in server we need this line:

res.header('Access-Control-Allow-Credentials', true)

This would let you handle credentials includes in headers.

You also have to tell to axios to set credentials in headers with:

withCredentials: true

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...