标签:Node code const res req js cookie path
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,code,const,res,req,js,cookie,path 来源: https://www.cnblogs.com/esrevinud/p/12771496.html
本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享; 2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关; 3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关; 4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除; 5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。