- 前言
和上一章(第八天就差了一个字), 要实现前后端分离的cookie登录验证, 需要结合第五天(服务端处理ajax跨域)和第八天(cookie登录逻辑)来完成
- 预备知识
默认情况下,由 JavaScript 代码发起的跨源请求不会带来任何凭据(cookies 或者 HTTP 认证(HTTP authentication))。
这对于 HTTP 请求来说并不常见。通常,对 http://site.com 的请求附带有该域的所有 cookie。但是由 JavaScript 方法发出的跨源请求是个例外。
例如,fetch或xm发起请求l(‘http://another.com’) 不会发送任何 cookie,即使那些 (!) 属于 another.com 域的 cookie
这是因为具有凭据的请求比没有凭据的请求要强大得多。如果被允许,它会使用它们的凭据授予 JavaScript 代表用户行为和访问敏感信息的全部权力。
跨域进行cookie通信, 必须前后端双方明确表示同意。
- 客户端XML发起的请求 必须设置
let ajax = new XMLHttpRequest(); ajax.withCredentials = true;
fetch发起的请求设置方式有一点区别, 但逻辑是完全相同的。
- 同时服务端除了处理常规跨域需要做的操作外还必须设置
res.setHeader('Access-Control-Allow-Credentials', 'true');
- 对于具有凭据的请求,禁止 Access-Control-Allow-Origin 使用星号 *。它必须有一个确切的源。这是另一项安全措施,以确保服务器真的知道它信任的是谁, 发出此请求的是谁。
- 前端, 简单模拟了一下单页面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>ajaxCookietitle>
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';
}
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>
- 后端, 前后端分离, 后端不处理页面逻辑. 只处理数据
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);
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);
- 现在流行的后台技术体系, 单页面app + 前后端分离 逻辑原型就是这样的~fun :-)