简体   繁体   English

如何使用hapi设置cookie?

[英]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 我阅读了hapi.js的官方文档,其代码与文档相似,但是无法设置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. 我想设置cookie但不能用,我的英语不是很好,我希望每个人都能宽容。

You should change isSecure to false in development. 在开发中,应将isSecure更改为false。 When it is set to true cookie is not set when there is no secure connection(https). 如果将其设置为true,则在没有安全连接(https)时不会设置cookie。

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
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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