简体   繁体   中英

Hapi.js Cookie not being set in browser

I am trying to set a cookie in my browser using Hapi.js. I followed the hapi.js documentation, and made sure that the isSecure option was set to false since I am using a http connection for dev purposes. However, I don't know why my cookie is not appearing under the cookies tab in chrome dev tools. I do however see it in my response header under the networks tab. Here is my code:

Server.js

//Set Cookie configuration
  server.state("loginCookie", {
    ttl: null,
    isSecure: false, //Must set to false for now. It will not work if true on a http connection
    isHttpOnly: true,
    encoding: "base64json",
    clearInvalid: true, //Want to remove invalid cookies
    strictHeader: true,
  });

user_routes.js

{
    method: "POST",
    path: "/signup",
    options: {
      validate: {
        payload: Joi.object({
          username: Joi.string().alphanum().min(4).max(16).required(),
          password: Joi.string().min(4).required(),
        }),
      },
      pre: [{ method: verifyUniqueUser }],
      auth: false,
    },

    handler: SignUpHandler,
  },

signUp.js

export const SignUpHandler = async (req, h) => {
  try {
    let user = new UserModel(req.payload);

    //Hash Password first before storing in user Model
    const { password, username } = req.payload;
    const hash = await bcrypt.hash(password, 8); 

    user.password = hash;

    await user.save();

    let token = jwt.sign(
      { id: user._id, username: username },
      process.env.SECRET_KEY,
      { algorithm: "HS256", expiresIn: "1h" }
    );

    console.log(token);

    h.state("loginCookie", token);

    return "Signed Up";
  } catch (error) {
    throw Boom.badRequest(error);
  }
};

My frontend portion that makes the request to my hapi server

const makeAccount = async () => {
      console.log(credentials);
      await axios.post("http://localhost:3001/signup", credentials);
    };

Any idea on what I could be doing wrong?

I found out that in order for my client to send and receive cookies, I had to add the withCredentials property in my axios request and set it to true. If you were to do this and you are also having a CORS error, make sure your server routes cors option has a credentials property set to true as well.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM