首页 / NODEJS / Node.js 使用cookie
Node.js 使用cookie
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了Node.js 使用cookie,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含1627字,纯文字阅读大概需要3分钟。
内容图文
![Node.js 使用cookie](/upload/InfoBanner/zyjiaocheng/634/d9cd74fdee52452bb5ea5a1d77d15b0c.jpg)
const http = require('http');
const querystring = require('querystring')
const PORT = 3000
const getExpires = () => {
let now = new Date();
now.setTime(now.getTime() + (30 * 60 * 1000))
return now.toGMTString();
}
const server = http.createServer((req, res) => {
res.setHeader('Content-Type', 'application/json')
let url = req.url;
req.path = url.split('?')[0];
req.query = querystring.parse(url.split('?')[1]);
// 忽略对favicon.ico的请求
if (req.path === '/favicon.ico') {
return;
}
if (req.path === '/login') {
if (req.query.username == 'admin' && req.query.password == 'helloworld') {
// path=/ 设置cookie在该域名下全局可以使用
// httpOnly 设置前端不能修改,修改了也会被覆盖
// expires 设置GMT格式时间戳
res.setHeader('Set-Cookie', `token=${req.query.username}; path=/; httpOnly; expires=${getExpires()}`)
res.end(JSON.stringify({
code : 200,
message : '登录成功',
data : null
}))
}
}
if (req.path === '/islogin') {
cookie = {};
let cookies = req.headers.cookie;
// 解析cookie
cookies.split(';').forEach(e => {
console.log(1)
let key = e.split('=')[0].trim();
let value = e.split('=')[1].trim();
cookie[key] = value;
})
if (cookie['token']) {
res.end(JSON.stringify({
code : 200,
message : `当前登录用户 -> ${cookie['token']}`,
data : null
}))
} else {
res.end(JSON.stringify({
code : 400,
message : '未登录',
data : null
}))
}
}
});
// 启动server
server.listen(PORT, () => {
console.log(`Application has running at port ${PORT}`)
});
登录http://localhost:3000/login?username=admin&password=helloworld
响应{"code":200,"message":"登录成功","data":null}
验证是否登录http://localhost:3000/islogin
响应{"code":200,"message":"当前登录用户 -> admin","data":null}
内容总结
以上是互联网集市为您收集整理的Node.js 使用cookie全部内容,希望文章能够帮你解决Node.js 使用cookie所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。