鏂囨。锛歂ode.js涓枃妗c€丼et-Cookie鍝嶅簲澶?br> 鍐呭锛氬姩鎬佹湇鍔″櫒
浠€涔堟槸鍔ㄦ€佹湇鍔″櫒?
闈欐€佹湇鍔″櫒(缃戦〉) VS 鍔ㄦ€佹湇鍔″櫒(缃戦〉)
鍒ゆ柇渚濇嵁
鏄惁璇锋眰浜嗘暟鎹簱銆?br>
娌℃湁璇锋眰鏁版嵁搴擄紝灏辨槸闈欐€佹湇鍔″櫒銆?strong>璇锋眰浜嗘暟鎹簱锛屽氨鏄姩鎬佹湇鍔″櫒銆?/strong>
浠婂ぉ鐩存帴鐢╦son鏂囦欢褰撲綔鏁版嵁搴撱€?br>
姝ラ 鏌ョ湅浠g爜
1.鏂板缓鐩綍db鍜屾枃浠秛sers.json
[
{"id":1,"name":"鏉庣櫧","password":"xxx","age":18},
{"id":2,"name":"鏉庡畤鏄?,"password":"yyy","age":20}
]
2.璇绘暟鎹簱
鏂板缓test.js鐢ㄦ潵娴嬭瘯鏁版嵁
fs鐢ㄦ潵璇绘枃浠剁殑锛岃鎯宠幏鍙栨枃浠舵暟鎹紝棣栧厛瑕佸紩鍏s銆?/p>
const fs = require('fs') //寮曞叆fs
const usersString = fs.readFileSync('./db/users.json').toString()
console.log(usersString)
toString() 鏂规硶杩斿洖涓€涓〃绀鸿瀵硅薄鐨勫瓧绗︿覆銆?br>
杩愯:node test.js
鎶婂瓧绗︿覆鍙樻垚鏁扮粍
const usersArray = JSON.parse(usersString)
console.log(typeof usersString)
console.log(usersString)
console.log(typeof usersArray)
console.log(usersArray)
console.log(usersArray instanceof Array)
3.鍐欐暟鎹簱
const user3 = { id: 3, name: '鏉庢槑', password: 'zzz', age: 25 }
usersArray.push(user3)
瀛樺埌鏁版嵁搴?/strong>銆傛垜浠殑鏁版嵁搴撴槸鏂囦欢锛屾枃浠跺彧鑳藉瓨瀛楃涓?/p>
姣忚繍琛屼竴娆?strong>node test.jsconsole.log(typeof user3) //object
const string = JSON.stringify(usersArray)
fs.writeFileSync('./db/users.json', string)
鐭ヨ瘑鐐癸細
1.JSON.stringify()搴忓垪鍖?瀛楃涓插寲
搴忓垪鍖栧氨鏄皢涓€涓猨s瀵硅薄鎴栧€艰浆鎹负绗﹀悎JSON璇硶瀛楃涓层€?br>
JSON.parse()鍙嶅簭鍒楀寲/鍙嶅瓧绗︿覆鍖?/strong>
鍙嶅簭鍒楀寲灏辨槸瑙f瀽JSON瀛楃涓诧紝鏋勯€犵敱瀛楃涓叉弿杩扮殑js鍊兼垨瀵硅薄銆?br>
2.json鏂囦欢娓呯┖鐨勮瘽蹇呴』鐣欎釜[]锛屼笉鐒朵細鎶ラ敊
3.UTF-8鐨勭紪鐮佹€庝箞鍙樻垚瀛楃涓诧紵
鐢?code>Buffer.concat(锛?/code>
渚嬪瓙:const string=Buffer.concat(array).toString()
4.js鏁扮粍浣跨敤JSON.stringify()鍜宼oString()鐨勫尯鍒?/strong>
toString()鏄皢鏁扮粍杞寲鎴愬瓧绗︿覆锛屽洜姝や笉甯]
JSON.stringify()灏嗕竴涓猨s瀵硅薄鎴栧€?涓€鑸槸瀵硅薄)杞崲涓虹鍚圝SON璇硶瀛楃涓?鏄甫[]鐨勩€?br>
鍙﹀JSON.parse()鏄В鏋怞SON瀛楃涓诧紝鏋勯€犵敱瀛楃涓叉弿杩扮殑js鍊兼垨瀵硅薄(涓€鑸槸瀵硅薄)
缁忛獙
1.璇绘暟鎹椂闇€瑕佸厛灏唈son鏁版嵁鏂囦欢toString()杞寲涓哄瓧绗︿覆锛岀鍚圝SON璇硶鐨勫瓧绗︿覆,toString涔熶細鍙?/strong>UTF-8缂栫爜銆傜劧鍚庡啀瑙f瀽JSON瀛楃涓睯SON.parse()鏋勯€犵敱瀛楃涓叉弿杩扮殑js鍊兼垨瀵硅薄銆?br>
JSON.parse()//[object Object],[object Object]
2.鍐欐暟鎹椂锛岄渶瑕佸皢鏁版嵁JSON.stringify()灏嗕竴涓猨s瀵硅薄鎴栧€艰浆鎹负绗﹀悎JSON璇硶瀛楃涓?鏄甫[]鐨勩€傚洜涓烘垜浠殑鏁版嵁搴撴槸鏂囦欢锛屾枃浠跺彧鑳藉瓨瀛楃涓层€?br>
鎬荤粨
/db/users.json
缁撴瀯锛氫竴涓暟缁?/strong>
[
{ id: 1, name: '鏉庣櫧', password: 'xxx', age: 18 },
{ id: 2, name: '鏉庡畤鏄?, password: 'yyy', age: 20 }
]
璇籾sers鏁版嵁
鍏坒s.readFileSync('./db/users.json).toString()
鐒跺悗JSON.parse涓€涓?鍙嶅簭鍒楀寲)锛屽緱鍒版暟缁?br>
鍐檜sers鏁版嵁
鍏圝SON.stringify涓€涓?搴忓垪鍖?锛屽緱鍒板瓧绗︿覆
鐒跺悗fs.writeFileSync('./db/users.json',data)
鐩爣1.瀹炵幇鐢ㄦ埛娉ㄥ唽鍔熻兘
鐢ㄦ埛鎻愪氦鐢ㄦ埛鍚嶅拰瀵嗙爜
users.json閲屽氨鏂板浜嗕竴琛屾暟鎹?br>
鎬濊矾
鍓嶇鍐欎竴涓猣orm,璁╃敤鎴峰~鍐檔ame鍜宲assword
鍓嶇鐩戝惉submit浜嬩欢
鍓嶇鍙戦€乸ost璇锋眰锛屾暟鎹綅浜庤姹備綋
鍚庣鎺ユ敹post璇锋眰
鍚庣鑾峰彇璇锋眰浣撲腑鐨刵ame鍜宲assword
鍚庣瀛樺偍鏁版嵁
姝ラ
棣栧厛锛屽厛璐ㄧ┖users.json鍙暀涓媅]
1.鏂板缓娉ㄥ唽椤甸潰register.html
2.閲嶇疆meta:vp鑳藉鍦ㄦ墜鏈轰笂杩愯
3.寮曞叆jQuery:鎴戜娇鐢ㄧ殑鏄疊ootCDN锛岄€夋嫨/jquery.min.js锛岀偣鍑诲鍒?code><script>鏍囩銆傚綋鐒朵綘涔熷彲浠ヤ娇鐢ㄤ竴浜涙洿楂樼骇鐨勫啓娉?姣斿npm)
蹇呴』鍏堝紩鍏query,鐒跺悗鎵嶈兘浣跨敤銆?br>
4.鐩戝惉琛ㄥ崟鐨剆ubmit浜嬩欢
琛ㄥ崟鏈夐粯璁や簨浠讹紝绗竴姝ュ氨鏄闃绘榛樿浜嬩欢锛屼笉闃绘鐨勮瘽浼氳嚜鍔ㄥ埛鏂伴〉闈?br>
5.鎷垮埌name鍜宲assword鍚庤鎻愪氦涓嬶紝鎬庝箞鎻愪氦鍛紵
鍙戜竴涓猘jax璇锋眰
<form id="registerForm">
<div>
<label>鐢ㄦ埛鍚?lt;input type="text" name="name"></label>
</div>
<div>
<label>瀵嗙爜<input type="password" name="password"></label>
</div>
<div>
<button type="submit">娉ㄥ唽</button>
</div>
</form>
<script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<script>
const $form = $('#registerForm')
$form.on('submit', (e) => {
e.preventDefault() //闃绘榛樿浜嬩欢
const name = $form.find('input[name=name]').val()
const password = $form.find('input[name=password]').val()
console.log(name, password)
$.ajax({
url: '/register',
data: JSON.stringify({
name, //name:name 鍐椾綑鍙缉鍐?
password ,
})
})
})
</script>
GET璇锋眰鍙兘鎶婃暟鎹斁鍒皍rl涓婇潰锛屾敼涓篜OST璇锋眰銆?/strong>
鎴戜滑涓婁紶缁欐湇鍔″櫒鐨勬槸json瀛楃涓诧紝閭f湇鍔″櫒鏄€庝箞鐭ラ亾鐨勫憿锛?/strong>
璁剧疆contentType
$.ajax({
method: 'POST',
url: '/register',
contentType: 'text/json;charset=UTF-8',
data: JSON.stringify({ name,password })
})
鑾峰彇post鏁版嵁
1.棣栧厛鍏堝鐞?register.html璇锋眰
server.js
if (path === '/register' && method === "POST") {
response.setHeader('Content-Type', 'text/html;charset=UTF-8')
response.end("浣犲ソ")
} else { ...}
2.鏈嶅姟鍣ㄥ浣曡幏鍙杗ame鍜宲assword鍛紵
GET璇锋眰鍙互閫氳繃query鎷垮埌锛孭OST璇锋眰鎬庝箞鎷垮埌锛?br>
鎬濊矾
(1)澹版槑涓€涓┖鏁扮粍鐢ㄦ潵瑁呮暟鎹€?/strong>鍥犱负鏁版嵁鏈夊彲鑳芥槸鍒嗘涓婁紶鐨勩€?br>
灏变袱鏉℃暟鎹负浠€涔堣繖涔堢偣鏁版嵁涔熻鍒嗘涓€涓竴涓笂浼狅紵
鍥犱负涓嶈兘纭畾浣犵殑鏁版嵁闀垮害鏄灏戙€備篃璁镐綘鍙紶涓猲ame銆乸assword锛屼絾涔熻浣犱篃鍙兘浼犱釜100鍏嗙殑鏂囦欢銆?00鍏嗙殑鏂囦欢涓婁紶鏄竴鐐逛竴鐐逛笂浼犵殑锛屾墍浠ユ垜浠湪鑾峰彇鏃朵篃瑕佷竴鏉′竴鏉¤幏鍙栥€?br>
(2)鐩戝惉璇锋眰涓婄殑鏁版嵁(data涓婁紶浜嬩欢)
server.js
const array = []
request.on('data', (chunk) => {
array.push(chunk) //鍏堜笂浼爊ame鍐嶄笂浼爌assword
})
request.on('end', () => { //缁撴潫鍚庡仛鐨勪簨鎯?
console.log(array)
const string=Buffer.concat(array).toString()
console.log(string)
response.end('寰堝ソ')
})
杩欏氨鏄疷TF-8鐨勭紪鐮侊紝鎬庝箞鍙樻垚瀛楃涓诧紵
鐢?code>Buffer.concat(锛?/code>
鍒繕浜咼SON.parse()瑙f瀽JSON瀛楃涓诧紝鏋勯€犵敱瀛楃涓叉弿杩扮殑js鍊兼垨瀵硅薄(涓€鑸槸瀵硅薄)銆?br> server.js
request.on('end', () => {
console.log(array)
const string = Buffer.concat(array).toString()
console.log(string)
const obj = JSON.parse(string)
console.log(obj.name)
console.log(obj.password)
response.end('寰堝ソ')
})
js銆乶ode.js銆佹祻瑙堝櫒閮芥湁鍏ㄥ眬鏂规硶JSON
鐜板湪鏈嶅姟鍣ㄥ氨鍙互鑾峰彇鎴戠殑name鍜宲assword浜嗐€?br>
濡備綍鑾峰彇褰撳墠id鍛紵
鎬濊矾锛氬厛璇诲啀鍐欍€傚厛璇诲嚭JSON鏁版嵁搴撲腑id鏈€澶х殑锛屼竴鑸槸鏈€鍚庝竴涓€傜劧鍚庡啀鍐?br>
server.js
if (path === '/register' && method === "POST") {
const userArray = JSON.parse(fs.readFileSync('./db/users.json').toString())
request.on('end', () => {
const lastUser = userArray[userArray.length - 1]
const newUser = {
//id涓烘渶鍚庝竴涓敤鎴风殑id+1
id: lastUser lastUser.id + 1 : 1, //濡傛灉鏄┖鐨勫氨缁欎釜淇濆簳鍊糹d:1
name: obj.name,
password: obj.password
}
userArray.push(newUser)
fs.writeFileSync('./db/users.json', JSON.stringify(userArray))
response.end()
})
}
}
娉ㄥ唽鎴愬姛鍚庤烦杞椤?/strong>
鏂板缓鐧诲綍椤祍ign_in.html
register.html
$.ajax({
...
}).then(() => {
alert("娉ㄥ唽鎴愬姛")
//window.open()
location.href = '/sign_in.html'
}, () => {})
})
then鐨勭1涓弬鏁版槸鎴愬姛锛岀2涓弬鏁版槸澶辫触
浠g爜鍏跺疄寰堢畝鍗曪紝鍙渶瑕佸紕鎳俬ttp鍗忚銆?strong>璁颁綇娴佺▼姣斾唬鐮佹洿閲嶈锛屾渶濂芥妸姣忎竴姝ョ殑娴佺▼璁颁笅鏉ワ紒
CSDN鐢ㄦ槑鏂囧瓨鍌ㄥ瘑鐮侊紵鎰忓杩樻槸鏁呮剰锛?br> 鐢╩d5鍔犲瘑鏄棬澶栨眽鐨勮涓?/p>
鐩爣2.瀹炵幇鐢ㄦ埛鐧诲綍鍔熻兘
棣栭〉home.html,宸茬櫥褰曠敤鎴峰彲鐪嬪埌鑷繁鍚?br>
鐧诲綍椤祍ign_in.html,鎻愪氦鐢ㄦ埛鍚嶅拰瀵嗙爜
杈撳叆鐨勭敤鎴峰悕鍜屽瘑鐮佸鏋滄槸鍖归厤鐨勶紝灏辫嚜鍔ㄨ烦杞椤?br>
sign_in.html鎬濊矾
鍓嶇鍐欎竴涓猣orm,璁╃敤鎴峰~鍐檔ame鍜宲assword
鍓嶇鐩戝惉submit浜嬩欢
鍓嶇鍙戦€乸ost璇锋眰锛屾暟鎹綅浜庤姹備綋
鍚庣鎺ユ敹post璇锋眰
鍚庣鑾峰彇璇锋眰浣撲腑鐨刵ame鍜宲assword
鍚庣璇诲彇鏁版嵁锛岀湅鏄惁鏈夊尮閰嶇殑name鍜宲assword
濡傛灉鍖归厤锛屽悗绔簲鏍囪鐢ㄦ埛宸茬櫥褰曪紝鍙槸鎬庝箞鏍囪锛?/p>
姝ラ
1.鏂板缓home.html
濡傛灉宸茬櫥褰曞氨鏄剧ず:鏉庨洩鑺?宸茬櫥褰曘€傚鏋滄湭鐧诲綍灏辨樉绀?鏈櫥褰曪紝璇风櫥褰?/p>
<p>浣犲ソ,{{user.name}}</p> //html涓嶈兘璇诲彇鏁版嵁搴擄紝鍙兘鐢ㄥ崰浣?
<p><a href="sign_in.html">鐧诲綍</a></p>
{{user.name}}鎬庝箞鏇挎崲锛?/strong> 鍗曠嫭鍐欎釜home鐨剆erver
if (path = "/home.html") {
//褰撳墠鐢ㄦ埛鏃犳硶寰楃煡锛屽啓涓嶅嚭鏉?
} else if (path === '/register' && method === "POST") {...}
2.缂栧啓sign_in.html锛岀櫥褰曟€濊矾涓庢敞鍐宺egister.html鎬濊矾鍩烘湰涓€鑷?/strong>
<form id="signInForm">
<div>
<label>鐢ㄦ埛鍚?lt;input type="text" name="name"></label>
</div>
<div>
<label>瀵嗙爜<input type="password" name="password"></label>
</div>
<div>
<button type="submit">鐧诲綍</button>
</div>
</form>
<script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<script>
const $form = $('#signInForm')
$form.on('submit', (e) => {
e.preventDefault()//闃绘榛樿浜嬩欢
const name = $form.find('input[name=name]').val()
const password = $form.find('input[name=password]').val()
console.log(name, password)
$.ajax({
method: 'POST',
url: '/sign_in',
contentType: 'text/json;charset=UTF-8',
data: JSON.stringify({ //鎶妌ame銆乸assword瀵硅薄鍙樻垚瀛楃涓蹭笂浼犵粰鏈嶅姟鍣?
name,
password
})
}).then(() => {
alert("鐧诲綍鎴愬姛")
location.href = '/sign_in.html'
}, () => {})
})
</script>
3.缂栧啓鍚庣閫昏緫
server.js
if (path === '/sign_in' && method === 'POST') {
const userArray = JSON.parse(fs.readFileSync('./db/users.json').toString())
const array = []
request.on('data', (chunk) => {
array.push(chunk)
})
request.on('end', () => {
const string = Buffer.concat(array).toString()
const obj = JSON.parse(string) //js銆乶ode.js娴忚鍣ㄩ兘鏈塉SON锛宯ame銆乸assword
//find()鏌ユ壘涓€涓暟缁勯噷鏈夋病鏈夌鍚堣姹傜殑
const user = userArray.find((user) => user.name === obj.name && user.password === user.password)
if(user === undefined){ //濡傛灉undefined璇存槑鐢ㄦ埛杩樻病鏈夋敞鍐屻€傝缃?00骞舵彁绀轰笉鍖归厤
response.statusCode = 400
//response.end('name password 涓嶅尮閰?)
response.setHeader('Content-Type', 'text/json;charset=UTF-8')
response.end(`{"errorCode":4001}`)
} else {
response.statusCode = 200
response.end()
}
})
} else if (path = "/home.html") {
//鍐欎笉鍑烘潵銆傝鍙栧綋鍓嶇敤鎴凤紝浣嗕笉鐭ラ亾褰撳墠鐢ㄦ埛鏄皝銆?
response.end('home')//鐩存帴杩斿洖涓€涓猦ome
} else if (path === '/register' && method === "POST") { ... }
} else { ... }
鐩存帴鎷疯礉鍦板潃(鏈€氳繃韬唤楠岃瘉)涓簎ndefined
濡傛灉鏄痷ndefined灏辫鏄巙ser鏄┖鐨勶紝鐢ㄦ埛鏈敞鍐屻€傝缃姸鎬佺爜400骞舵彁绀烘姤閿欑殑鍐呭
涓€鑸姹傚瓧绗︿覆娌′粈涔堢敤锛屾渶濂芥槸鑳借繑鍥炰釜JSON鐒跺悗缁欏畠涓敊璇爜銆?/strong>
response.setHeader('Content-Type', 'text/html;charset=UTF-8') //鍛婅瘔娴忚鍣ㄦ垜鏄疛SON
response.end(`{"errorCode":4001}`)
涓轰粈涔?001灏辨槸"鐢ㄦ埛鍚嶅瘑鐮佷笉鍖归厤"鍛紵
渚嬪瓙:4001琛ㄧず鏄?00鐨勭1绉嶉敊璇€?br>
杩欎釜鏄綘鑷繁鍦ㄦ枃妗i噷鍐欑殑锛屼綘鎰挎剰鍐?001琛ㄧず鐢ㄦ埛鍚嶅瘑鐮佷笉鍖归厤锛岄偅4001灏辨槸銆?br>
姣忎釜鍏徃閮芥湁鑷繁鐨別rrorCode缂栫爜锛屽鏋滄病鏈夐偅灏辫鏄庡叕鍙稿緢鎸€?br>
鏈敞鍐屾椂锛?/strong>
鐭ヨ瘑鐐?/strong>
1.馃攳mdn array find鏌ユ壘鏁扮粍閲屾湁娌℃湁绗﹀悎瑕佹眰鐨勩€?br>
娴忚鍣ㄥ吋瀹规€э細IE涓嶆敮鎸侊紝node.js鏀寔灏辫浜嗐€?br>
鐢ㄦ硶
const array1 = [5, 12, 8, 130, 44];
const found = array1.find(element => element > 10);
console.log(found); // expected output: 12
find() 鏂规硶杩斿洖鏁扮粍涓弧瓒虫彁渚涚殑娴嬭瘯鍑芥暟鐨勭涓€涓厓绱犵殑鍊笺€傚惁鍒欒繑鍥?undefined銆?br>
渚嬪瓙
find閲岄潰鍐欎釜鍑芥暟,鍑芥暟鍐呭:婊¤冻鏉′欢灏辫繑鍥瀟rue,濡傛灉鏈夎繖涔堜釜瀵硅薄灏辫繑鍥炲嚱鏁扮殑绗?涓厓绱犲€笺€?/p>
const user=userArray.find((user) => user.name === obj.name && user.password === obj.password)
2.400,4寮€澶寸殑鍝嶅簲statusCode琛ㄧず閮芥槸閿欑殑
response.statusCode = 400
3.绛夊緟鐘舵€?/strong>
褰撴病缂栧啓(path = "/home.html"鐨勯€昏緫鏃讹紝娴忚鍣ㄥ氨浼氫竴鐩村浜庣瓑寰呯姸鎬侊紝蹇呴』鍐欑偣鍐呭銆?br> 娌℃湁response.end()涔熶細瀵艰嚧涓€鐩村浜?璇锋眰鐘舵€?,璁板緱end
鎬荤粨锛氱洰鏍?鍙楅樆锛岀洰鏍囧お澶т簡锛岀洰鏍囧簲璇ュ敖閲忓皬銆?br> 鎶婄洰鏍囪皟灏忕偣锛屼綘鑳芥兂鍒扮殑鐩爣涓庝綘鐨勮兘鍔涗笉鍖归厤锛屾墍浠ヤ綘闇€瑕佹湁缁忛獙鐨勪汉缁欎綘瀹氱洰鏍囥€?br> 鏀逛竴涓嬶紝杩欐涓嶈鏄剧ず鐢ㄦ埛鍚嶄簡锛屾爣璁扮敤鎴峰凡缁忕櫥褰曘€?/p>
鐩爣3.鏍囪鐢ㄦ埛宸茬櫥褰?
浣跨敤Cookie鏍囪鐢ㄦ埛
home.html
<p>{{loginStatus}}</p>
<p><a href="sign_in.html">鐧诲綍</a></p>
鎶妉oginStatus鍙樻垚true(鐧诲綍)鎴杅alse(鏈櫥褰?
濡備綍璇嗗埆涓€涓敤鎴锋槸鍚︾櫥褰曪紵 浣跨敤Cookie鏍囪鐢ㄦ埛
Cookie
瀹氫箟
Cookie鏄湇鍔″櫒涓嬪彂缁欐祻瑙堝櫒鐨勪竴娈靛瓧绗︿覆
娴忚鍣ㄥ繀椤讳繚瀛樿繖涓狢ookie(闄ら潪鐢ㄦ埛鍒犻櫎)
涔嬪悗鍙戣捣鐩稿悓浜岀骇鍩熷悕璇锋眰(浠讳綍璇锋眰)鏃讹紝娴忚鍣ㄥ繀椤婚檮涓奀ookie
涓句緥璇存槑
鍋囧浣犳槸鍏洯妫€绁ㄥ憳锛屼綘鎬庝箞鐭ラ亾璋佽兘杩涜皝涓嶈兘锛熸湁绁ㄨ兘杩涳紝娌$エ涓嶈兘杩涖€?br>
Cookie灏辨槸闂ㄧエ
鏈塁ookie灏辨槸鐧诲綍浜嗭紝娌ookie灏辨病鐧诲綍
閭e悗绔粰娴忚鍣ㄤ笅鍙戜竴涓狢ookie涓嶅氨瀹屼簨浜嗗槢
浠g爜
response.setHeader('Set-Cookie','logined=1')//鍙戠エ锛?鏄痶rue
璇荤エ
馃攳nodejs request cookie
const cookie = request.headers['cookie']
濡傛灉鐧诲綍杩囦簡logined=1锛屾病鐧诲綍灏眜ndefined銆?/strong>
else if (path === '/home.html') {
//console.log(request.headers)
const cookie = request.headers['cookie']
if (cookie === 'logined=1') {
const homeHtml = fs.readFileSync('./public/home.html').toString()
const string = homeHtml.replace('{{loginStatus}}', '宸茬櫥闄?)
response.write(string)
//console.log(cookie)
} else {
const homeHtml = fs.readFileSync('./public/home.html').toString()
const string = homeHtml.replace('{{loginStatus}}', '鏈櫥闄?)
response.write(string)
}
鐭ヨ瘑鐐?/strong>
1.response.setHeader鐨勫悇绉嶇敤娉?br>
2.馃攳mdn set cookie
璇硶:Set-Cookie:<cookie-name>=<cookie-value>
浣跨敤:鐧诲綍鎴愬姛鏃惰姹傚ごcookie
response.setHeader('Set-Cookie','logined=1') //1鏄痶rue锛孲et-Cookie:name=value
Set-Cookie鐨勫叾瀹冨弬鏁?
Expires=<date>璁剧疆涓€涓繃鏈熺殑鏃堕棿锛屾椂闂翠竴杩囨湡锛岀エ灏变笉浼氬埌浣犺韩涓婁簡銆?br>
Max-Age鏈€澶ф椂闂达紝杩囦簡杩欐鏃堕棿绁ㄤ篃涓嶄細鍒颁綘韬笂浜嗐€?br>
Domain鍩熷悕銆丳ath璺緞銆丼ecure鏄惁鍙湪https鏃堕檮甯?br>
HttpOnly涓嶅噯鍓嶇纰版垜鐨刢ookie,鍓嶇鑳芥敼璇存槑鐢ㄦ埛灏辫兘鏀?鍚庣瑕佸潥鍐虫潨缁濆墠绔慨鏀逛竴瀹氳鍔燞ttpOnly
Set-Cookie: id=a3fWa; Expires=Wed, 21 Oct 2015 07:28:00 GMT; Secure; HttpOnly
3.request.headers銆乺equest.getHeader銆乺equest.getHeaders銆乺equest.getHeaderNames鍖哄埆
request.headers['Cookie'];
request.getHeader("Accept-Encoding");鑾峰彇鍗曚釜璇锋眰澶磏ame瀵瑰簲鐨剉alue鍊?
request.getHeaders("Accept-Encoding")鑾峰彇澶氫釜鍚屽悕璇锋眰澶村搴旂殑涓€缁剉alue鍊硷紝鍥犳杩斿洖鏋氫妇绫诲瀷鏁版嵁
request.getHeaderNames();鑾峰彇璇锋眰澶寸殑鎵€鏈塶ame鍊?杩斿洖鐨勬暟鎹篃鏄竴涓灇涓剧被鍨嬬殑鏁版嵁锛?
灏嗘灇涓句腑鐨勫厓绱犱緷娆¢亶鍘嗗嚭鏉ワ紝鏍规嵁name鑾峰彇瀵瑰簲鐨剉alue鍊硷紝鍗冲彲寰楀埌Http璇锋眰澶寸殑鎵€鏈変俊鎭?
4.娉ㄦ剰锛歠s.readFileSync璇绘枃浠跺悗鏈€濂絫oString,鍥犱负榛樿涓嶆槸涓€涓猄tring
杩斿洖鍊煎彲鑳芥槸String锛屼篃鍙兘鏄?strong>Buffer绫诲瀷锛岄粯璁や笉鏄痵tring
.toString()鑳界‘淇濇槸String绫诲瀷锛屽悗闈㈢殑JSON.parse鎵嶈兘姝e父澶勭悊
5.cookie鏄惁鍙兘鍚庣璁剧疆锛?br>
涓嶆槸锛屼絾鏄缓璁案杩滃彧鍦ㄥ悗绔缃甤ookie锛屽墠绔痡s鍗冧竾涓嶈纰癱ookie銆?br>
cookie鏄惁鑳戒吉閫狅紵
浣跨敤Cookie璁板綍user id
home.html鎬庝箞鐭ラ亾鐧诲綍鐨勬槸璋佸憿锛?/strong>
閫氳繃cookie閲岄潰瀛樼殑id灏辩煡閬撲簡銆?br>
鎬濊矾:鎶妉ogined鏀规垚user_id锛寀ser_id鍘绘嬁杩欎釜user锛寀ser瀛樺湪灏辨妸杩欎釜userName鏇挎崲鍒伴〉闈腑銆?br>
杩欐牱home灏辩煡閬撲簡褰撳墠鐧诲綍鐨勭敤鎴锋槸璋佷簡
if (path === '/sign_in' && method === 'POST') {
request.on('end', () => {
if(user === undefined){
...
}else{
response.statusCode = 200
response.setHeader('Set-Cookie', `user_id=${user.id}; HttpOnly`)
response.end()
}
}
}
鑾峰彇userId
else if (path === '/home.html') {
const cookie = request.headers["cookie"]
console.log(cookie)
let userId
try { //娌℃湁userId鍙兘浼氭姤閿?
userId = cookie.split(';').filter(s => s.indexOf('user_id=') >= 0)[0].split('=')[1]
} catch (error) { }
瑙f瀽锛歔 'logined=1', ' user_id=2' ]
cookie.split(';').filter(s => s.indexOf('user_id=') < 0) //[ 'logined=1' ]
cookie.split(';').filter(s => s.indexOf('user_id=') >= 0)[0]鍥犱负鏄暟缁勶紝鎵€浠ュ彇绗?涓紝user_id=2
鐜板湪鍙渶瑕佸垽鏂槸鍚︽湁userId鍗冲彲
if (userId) {
const userArray = JSON.parse(fs.readFileSync('./db/users.json'))
const user = userArray.find(user => user.id.toString() === userId)
let string
if (user) {
string = homeHtml.replace('{{loginStatus}}', '宸茬櫥闄?).replace('{{user.name}}', user.name)
} else { }
response.write(string)
} else {
const homeHtml = fs.readFileSync('./public/home.html').toString()
const string = homeHtml.replace('{{loginStatus}}', '鏈櫥闄?).replace('{{user.name}}', '')
response.write(string)
}
user鍙兘鏈変篃鍙兘娌℃湁銆?/strong> 鏄剧ず鐢ㄦ埛鍚?/strong> Bug:鐢ㄦ埛鍙互绡℃敼user_id 2.浣跨敤js鑷甫鐨勯殢鏈烘暟,杩樿鎶婇殢鏈烘暟璁板埌鎴戠殑鏂囦欢session閲岄潰 鎶奿d缁欐祻瑙堝櫒锛屾祻瑙堝櫒骞朵笉鐭ラ亾id瀵瑰簲鐨勫暐锛岄偅鎴戞€庝箞鐭ラ亾鍛紵鎴戠殑session.json璁板綍浜嗐€?/p>
3.home鎬庝箞鑾峰彇user_id? session鐨勬椂鏁堟€? 鏁版嵁閫氳繃鏂囦欢鎿嶄綔鏃跺彲鐢ㄦ€у緢寮猴紝鍥犱负鏁版嵁鏄湪鏈嶅姟鍣ㄤ笂鐨勶紝Session淇濆瓨鍦ㄦ湇鍔″櫒鐨勬枃浠朵腑銆傚彲浠ラ殢鏃跺垹鎺夋湁闂鐨剆esstionId銆傛湇鍔″櫒涓€鑸細灏哠ession id鏀惧埌Cookie涓紝鍙戞斁缁欐祻瑙堝櫒銆?br>
鍔犲瘑鏁版嵁鏄湪鐢ㄦ埛閭h竟鐨勶紝鏃犳硶淇敼銆?br>
鎬濊矾2锛屽姞瀵?/strong> 娉ㄩ攢鍔熻兘涓€鑸浣曞疄鐜?
濡傛灉鏈塽ser璇存槑宸茬櫥褰曪紝濡傛灉娌℃湁user璇存槑娌$櫥褰曘€?br>
濡傛灉宸茬櫥褰曟椂灏嗙敤鎴峰悕鍛婅瘔鎴戯紝濡傛灉鏈櫥褰曟妸user.name缁欏垹鎺?/p>
home.html娓叉煋鍓嶈幏鍙杣ser淇℃伅
濡傛灉鏈塽ser,鍒欏皢{{user.name}}鏇挎崲鎴恥ser.name
濡傛灉鏃爑ser,鍒欐樉绀虹櫥褰曟寜閽?/p>
home.html
<p>
{{user.name}}
{{loginStatus}}
</p>
鐩爣4.闃茬鏀箄ser_id
濡傛灉鏄疕ttpOnly鍙兘鐢ㄥ紑鍙戣€呭伐鍏锋敼锛屽鏋滄病鏈塇ttpOnly閭S灏辫兘鏀广€?br>
濡備綍瑙e喅鐢ㄦ埛绡℃敼cookie鐨勯棶棰橈紵
鎬濊矾1锛屾妸淇℃伅闅愯棌鍦ㄦ湇鍔″櫒锛屾帹鑽?/strong>
鐢ㄩ殢鏈烘暟
鎶婄敤鎴蜂俊鎭斁鍦ㄦ湇鍔″櫒鐨刋閲岋紝鍐嶇粰淇℃伅涓€涓殢鏈篿d
鎶婇殢鏈篿d鍙戠粰娴忚鍣?br>
鍚庣涓嬫璇诲彇鍒癷d鏃讹紝閫氳繃x[id]鑾峰彇鐢ㄦ埛淇℃伅
鎯虫兂涓轰粈涔堢敤鎴锋棤娉曠鏀筰d(鍥犱负id寰堥暱锛岃€屼笖闅忔満)
x鏄粈涔堬紵鏄枃浠躲€備笉鑳界敤鍐呭瓨锛屽洜涓烘柇鐢靛唴瀛樺氨娓呯┖
杩欎釜x鍙堣鍙仛session(浼氳瘽)
姝ラ
1.鏂板缓鏂囦欢session.json(鐢ㄤ粈涔堝舰寮忔棤鎵€璋?
session.json榛樿鏄釜瀵硅薄
濡傛灉鎴戠粰娴忚鍣ㄨ繖涓暟瀛?0.05239442708348885),鎰忔€濆氨鏄垜缁欎簡浣犺繖涓璞?user_id鏄?)锛岃〃椹卞姩缂栫▼銆?/p>
{
// "0.05239442708348885":{"user_id":2} 璁板緱娓呯┖锛屽唴瀹规槸鑷姩鐢熸垚鐨勬棤闇€鎵嬪啓銆?
}
request.on('end', () => {
if (user === undefined) {
...
} else {
response.statusCode = 200;
const random = Math.random()
const session = JSON.parse(fs.readFileSync('./session.json').toString())
session[random] = { user_id: user.id }
fs.writeFileSync('./session.json', JSON.stringify(session))
response.setHeader("Set-Cookie", `session_id=${random}; HttpOnly`);
}
response.end()
});
//let userId
let sessionId
try {
sessionId=cookie.split(';').filter(s => s.indexOf('sessionId=') >= 0)[0].split('=')[1]
} catch (error) { }
const session = JSON.parse(fs.readFileSync('./session.json').toString())
if (sessionId && session[sessionId]) {
const userId = session[sessionId].user_id
const userArray = JSON.parse(fs.readFileSync("./db/users.json"));
const user = userArray.find(user => user.id === userId);
const homeHtml = fs.readFileSync("./public/home.html").toString();
let string = ''
if (user) {
string = homeHtml.replace("{{loginStatus}}", "宸茬櫥褰?)
.replace('{{user.name}}', user.name)
}
response.write(string);
} else {
const homeHtml = fs.readFileSync("./public/home.html").toString();
const string = homeHtml.replace("{{loginStatus}}", "鏈櫥褰?)
.replace('{{user.name}}', '')
response.write(string);
}
response.end()
灏唘ser_id鍔犲瘑鍙戦€佺粰鍓嶇锛屽悗绔鍙杣ser_id鏃惰В瀵嗭紝姝ゆ硶鍙浣嗘湁瀹夊叏婕忔礊銆?br>
婕忔礊锛氬姞瀵嗗悗鐨勫唴瀹瑰彲浠ユ棤闄愭湡浣跨敤娌″姙娉曟敞閿€鎺?/strong>锛屽鏋滆绐冨惉鑰呮嬁鍒颁簡鍔犲瘑鐨剈ser_id锛屼粬灏卞彲浠ヤ竴鐩寸敤杩欎釜鍔犲瘑鐨剈ser_id澶嶅埗鍒颁粬鐨勬祻瑙堝櫒涓婏紝鐒跺悗涓嶅仠鐨勬ā鎷熶綘鐧诲綍銆?br>
瑙e喅鍔炴硶锛欽WT
瀹夊叏璧疯锛屼笉鑳界敤JS鍒燙ookie锛屽簲璇ヤ娇鐢℉ttpOnly鐨凜ookie锛岀劧鍚嶫S鍙戣姹傝鏈嶅姟鍣ㄥ垹 Cookie
瀹夊叏璧疯锛岄櫎浜嗗垹闄ゆ祻瑙堝櫒绔殑Cookie锛岃繕闇€瑕佹妸瀵瑰簲鐨凷ession鏁版嵁鍒犳帀