node 第九天 使用前后端分离的方式实现cookie登录验证(关于withCredentials)

编程入门 行业动态 更新时间:2024-10-11 19:25:33

node 第九天 使用前<a href=https://www.elefans.com/category/jswz/34/1771414.html style=后端分离的方式实现cookie登录验证(关于withCredentials)"/>

node 第九天 使用前后端分离的方式实现cookie登录验证(关于withCredentials)

  1. 前言
    和上一章(第八天就差了一个字), 要实现前后端分离的cookie登录验证, 需要结合第五天(服务端处理ajax跨域)和第八天(cookie登录逻辑)来完成
  2. 预备知识
    默认情况下,由 JavaScript 代码发起的跨源请求不会带来任何凭据(cookies 或者 HTTP 认证(HTTP authentication))。
    这对于 HTTP 请求来说并不常见。通常,对 的请求附带有该域的所有 cookie。但是由 JavaScript 方法发出的跨源请求是个例外。
    例如,fetch或xm发起请求l(‘’) 不会发送任何 cookie,即使那些 (!) 属于 another 域的 cookie
    这是因为具有凭据的请求比没有凭据的请求要强大得多。如果被允许,它会使用它们的凭据授予 JavaScript 代表用户行为和访问敏感信息的全部权力。
    跨域进行cookie通信, 必须前后端双方明确表示同意。
  • 客户端XML发起的请求 必须设置 let ajax = new XMLHttpRequest(); ajax.withCredentials = true; fetch发起的请求设置方式有一点区别, 但逻辑是完全相同的。
  • 同时服务端除了处理常规跨域需要做的操作外还必须设置res.setHeader('Access-Control-Allow-Credentials', 'true');
  • 对于具有凭据的请求,禁止 Access-Control-Allow-Origin 使用星号 *。它必须有一个确切的源。这是另一项安全措施,以确保服务器真的知道它信任的是谁, 发出此请求的是谁。
  1. 前端, 简单模拟了一下单页面app的前端路由, 自己封装了一个简单ajax, 当然也可以使用axios, jQuery的$.ajax()等请求库
<!DOCTYPE html>
<html lang="en"><head><meta charset="UTF-8" /><meta name="viewport" content="width=device-width, initial-scale=1.0" /><title>ajaxCookie</title></head><body><div id="login" style="display: none"><h1>请登录:</h1><input id="password" name="pw" type="password" /><input id="submit" type="submit" value="登录" /></div><div id="content" style="display: none"><h1>欢迎您~</h1></div></body><script>function myAjax({method = 'GET',url = '/',data = {},headers = {'content-type': 'application/x-www-form-urlencoded'},responseType = 'text',withCredentials = false,success = res => {console.log(res);},error = err => {console.log(err);}}) {let ajax = new XMLHttpRequest();ajax.withCredentials = withCredentials;ajax.open(method, url);for (const key in headers) {if (Object.hasOwnProperty.call(headers, key)) {ajax.setRequestHeader(key, headers[key]);}}ajax.responseType = responseType;ajax.send(data);ajax.onreadystatechange = () => {if (ajax.readyState === 4) {success(ajax.response);}};ajax.onerror = err => {error(err);};}</script><script>const loginEl = document.querySelector('#login');const submitEl = document.querySelector('#submit');const contentEl = document.querySelector('#content');//前端控制路由function toLogin() {loginEl.style.display = 'block';contentEl.style.display = 'none';}function toContent() {loginEl.style.display = 'none';contentEl.style.display = 'block';}//进入即发起请求(不携带密码, 携带cookie)myAjax({method: 'POST',url: 'http://127.0.0.1:3007/ajax',data: JSON.stringify({}),headers: {'content-type': 'application/json','x-token': 'x-token'},responseType: 'json',withCredentials: true,success: res => {console.log(res);if (res.code === 1) {this.toContent();} else {this.toLogin();}},err: err => {console.log(err);}});submitEl.onclick = () => {let pw = document.querySelector('#password').value;myAjax({method: 'POST',url: 'http://127.0.0.1:3007/login',data: JSON.stringify({pw: pw}),headers: {'content-type': 'application/json','x-token': 'x-token'},responseType: 'json',withCredentials: true,success: res => {console.log(res);if (res.code === 1) {this.toContent();} else {this.toLogin();}},err: err => {console.log(err);}});};</script>
</html>
  1. 后端, 前后端分离, 后端不处理页面逻辑. 只处理数据
const fs = require('fs');
const url = require('url');
const http = require('http');
const querystring = require('querystring');
const path = require('path');const server = http.createServer((req, res) => {res.setHeader('Access-Control-Allow-Origin', 'http://127.0.0.1:5500');res.setHeader('Access-Control-Allow-Headers', 'Content-Type, x-token');res.setHeader('Access-Control-Allow-Credentials', 'true');res.setHeader('Access-Control-Allow-Methods', 'POST, GET, PUT, OPTIONS, DELETE');res.setHeader('Access-Control-Max-Age', 1728000); //预请求缓存20天if (req.method === 'OPTIONS') {res.writeHead(200);res.end();} else {let cookie = req.headers.cookie;cookie = cookie.replace(/\s/g, '');const cookieInfo = querystring.parse(cookie, ';');if (cookieInfo.token === '10086') {res.writeHead(200, {'content-type': 'application/json'});res.end(JSON.stringify({ code: 1, data: { name: 'jian' }, msg: '登录成功' }));} else if (req.url === '/login') {req.on('data', chunk => {let { pw } = JSON.parse(chunk.toString('utf-8'));if (pw === '123456') {let date = new Date();date.setDate(date.getDate() + 1);let expires = date.toUTCString();res.writeHead(200, {'content-type': 'application/json','set-cookie': [`token=10086; Expires=${expires}; HttpOnly;`]});res.end(JSON.stringify({ code: 1, data: { name: 'jian' }, msg: '登录成功' }));} else {res.writeHead(200, {'content-type': 'application/json'});res.end(JSON.stringify({ code: 0, data: {}, msg: '密码错误' }));}});} else {res.writeHead(200, {'content-type': 'application/json'});res.end(JSON.stringify({ code: 0, data: {}, msg: '未登录' }));}}
});
server.listen(3007);
  1. 现在流行的后台技术体系, 单页面app + 前后端分离 逻辑原型就是这样的~fun :-)

更多推荐

node 第九天 使用前后端分离的方式实现cookie登录验证(关于withCredentials)

本文发布于:2023-12-06 21:57:08,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1669065.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:后端   方式   第九天   node   cookie

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!