简体   繁体   中英

how to use hapi to set cookie?

I read the official documentation of hapi.js, the code is similar to the documentation, but it is impossible to set a cookie

const Hapi=require('hapi');
const server = Hapi.server({
    host:'localhost',
    port:3333
});

server.state('user', {
    ttl: 24 * 60 * 60 * 1000,     // One day
    isSecure: true,
    isHttpOnly: true,
    encoding: 'base64json',
    clearInvalid: false,
    strictHeader: true
});
server.route({
    method:'POST',
    path:'/login',
    handler:function(request,h) {
        var data = request.payload;

        if(data.account === "a" && data.password === "a"){
            h.state('user', { account: "shmily" });

            console.log(request.state.user); //undefined

            return h.response('success');
        }else{
            return "wrong";
        }

    }
});
async function start() {
    try {
        await server.start();
    }
    catch (err) {
        process.exit(1);
    }
    console.log('服务器开启了3333端口!');
};
start();

I want to set the cookie but it does not work.My English is not very good, I hope everyone can be more tolerant.

You should change isSecure to false in development. When it is set to true cookie is not set when there is no secure connection(https).

So change your code so it looks like this

server.state('user', {
   ttl: 24 * 60 * 60 * 1000,     // One day
   isSecure: false,
   isHttpOnly: true,
   encoding: 'base64json',
   clearInvalid: false,
  strictHeader: true
});

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