Main Functions
The q&A system mainly realizes the functions of registering and logging in, asking and answering questions, updating the profile picture and exiting the login.
Registration module
var psw = $('#password').val()
var again = $("#again").val()
if(user.length < 6){
alert('Account number must be no less than 6')
return
}
if(psw.length < 6){
alert('Password must be no less than 6 characters')
return
}
if(psw ! = again){ alert('Two different passwords')
return
}
var xhr = new XMLHttpRequest()
xhr.open('post' , '/regist')
xhr.setRequestHeader("Content-Type" , 'application/x-www-form-urlencoded')
xhr.send(`account=${user}&password=${psw}`)
xhr.onreadystatechange = function(){
if(xhr.readyState == 4) {if(xhr.responseText == 'Registration successful'){
location.href = 'login.html'
}
else{
alert(xhr.responseText)
}
}
}
}
Copy the code
The login module
var psw = $('#password').val()
if(user.length < 6){
alert('Account number must be no less than 6')
return
}
if(psw.length < 6){
alert('Password must be no less than 6 characters')
return
}
var xhr = new XMLHttpRequest()
xhr.open('post' , '/login')
xhr.setRequestHeader("Content-Type" , 'application/x-www-form-urlencoded')
xhr.send(`account=${user}&password=${psw}`)
xhr.onreadystatechange = function(){
if(xhr.readyState == 4) {if(xhr.responseText == 'Login successful'){
location.href = 'index.html'
}
else{
alert(xhr.responseText)
}
}
}
}
Copy the code
Questions page
if(question.length == 0){
alert('The question cannot be empty')
return
}
var xhr = new XMLHttpRequest()
xhr.open('post' , '/question')
xhr.setRequestHeader("Content-Type" , 'application/x-www-form-urlencoded')
xhr.send(`question=${question}&user=${$.cookie("loginName")}`)
xhr.onreadystatechange = function(){
if(xhr.readyState == 4) {if(xhr.responseText == 'Successful question'){
location.href = 'index.html'
}
else{
alert(xhr.responseText)
}
}
}
}
Copy the code
The main page
$('#dropdown').removeClass('hide').addClass('show')
var cookieName = $.cookie('loginName')
function getHeader(){
var xhr = new XMLHttpRequest()
xhr.open('get' , '/getHeader')
xhr.send()
xhr.onreadystatechange = function(){
if(xhr.readyState == 4){
$('#header').attr('src' , xhr.responseText)
}
}
}
if (cookieName) {
// If there are cookies, login
$('#regist').addClass('hide'The $()'#dropdown').removeClass('hide').addClass('show'The $()'#header').addClass('show').removeClass('hide'The $()'#name').text(cookieName)
// Get the avatar of the current logged-in person
getHeader()
}
else {
// Log out
$('#regist').addClass('show').removeClass('hide'The $()'#dropdown').removeClass('show').addClass('hide'The $()'#header').addClass('hide').removeClass('show')}// Log out
function logout() {
$.removeCookie('loginName')
window.location.href = '/'
}
/ / questions
function toQuestion() {
if (cookieName) {
location.href = 'question.html'
}
else {
window.location.href = 'login.html'}}function getAllQuestion() {
var xhr = new XMLHttpRequest()
xhr.open('get'.'/getQuestion')
xhr.send()
xhr.onreadystatechange = function () {
if (xhr.readyState == 4) {
var questionList = JSON.parse(xhr.responseText)
var html = ' '
for (var index = 0; index < questionList.length; index++) {
var question = questionList[index]
html += `
<div class="panel panel-danger getMargin">
<div class="panel-heading">
<h3 class="panel-title">
${question.asker}
<img class="header" src='${question.header}'>
${question.time}
</h3>
</div>
<div class="panel-body questionPanel">
<div class="questionContent"> ${question.content} </div>
<button onclick="clickToAnswer(${index}</button> <div class='answerPanel'></div> </div>
var answerHtml = ' '
for (var a = 0; a < question.answerList.length; a++) {
var answer = question.answerList[a]
answerHtml += `
<div class="panel panel-success dropMargin " style="text-align:right">
<div class="panel-heading">
<h3 class="panel-title">
${answer.answerMan}
<img class="header" src='${answer.header}'>
${answer.time}
</h3>
</div>
<div class="panel-body questionPanel">
<div class="questionContent"> ${answer.content} </div>
</div>
</div>
`
}
// Put the questions and answers together
html += answerHtml
}
$('#list').html(html)
}
}
}
getAllQuestion()
function clickToAnswer(index) {
if (cookieName) {
// Pop up the modal box
$('#myModal').modal('show')
// Keep the index of the problem
$.cookie('index', index)
}
else {
location.href = 'login.html'}}function sendAnswer() {
var content = $('textarea').val()
if (content.length == 0) {
alert('Content cannot be empty')
return
}
var xhr = new XMLHttpRequest()
xhr.open('post'.'/sendAnswer')
xhr.setRequestHeader('Content-Type'.'application/x-www-form-urlencoded')
// Index the respondents to the content questions
xhr.send(`content=${content}&index=${$.cookie('index')}&answerMan=${cookieName}`)
xhr.onreadystatechange = function () {
if (xhr.readyState == 4) {
// console.log(xhr.responseText);
// Hide the modal box
$('#myModal').modal('hide')
// Empty the input
$('textarea').val("")
// Get the latest content
// location.href = '/'
location.reload()
}
}
}
Copy the code
Write the back end using Node.js
var allUserArray = [] fs.access('allUser.txt', function(noExists){ if(noExists){ fs.writeFileSync('allUser.txt' , JSON.stringify(allUserArray)) } else{ fs.readFile("allUser.txt", 'utf-8' , function(err , data){ allUserArray = JSON.parse(data) }) } }) var headerName = '' var diskStorage = multer.diskStorage({ destination:function(req ,file , callback){ callback(null , './public') }, filename(req , File,callback){// file.originalName 2152.1.3.43.png var splitArray = file.originalname.split('.') // Get the image format Var type = splitArray[splitarray.length-1] // Splitarray.length-1 [splitarray.length-1] headerName = './header/' + req.cookies. LoginName + '.' + type console.log(headerName); Var index = allUserArray.findIndex(function(el){return el.account ==) var index = allUserArray.findIndex(function(el){return el.account == Req.cookies. LoginName}) // Set the user profile picture to the latest profile picture allUserArray[index]. Header = headerName fs.writefile (" alluser.txt ", JSON.stringify(allUserArray), function(err){ }) callback(null , Var allQuestionArray = [] fs.access('question.txt',function(noExists){if(noExists){ fs.writeFileSync('question.txt' , JSON.stringify(allQuestionArray)) } else{ fs.readFile('question.txt' , 'utf-8' , function(err , Data){allQuestionArray = json.parse (data)})}}) // Register web.post('/regist',function(req,res){console.log(req.body); for(var index = 0 ; index < allUserArray.length ; Index ++){var user = allUserArray[index] if(user.account == req.body.account){res.send(' this account is registered ') return}} // Header = './header/default.png' allUserArray.push(req.body) fs.writefile (' alluser.txt ', JSON.stringify(allUserArray) , Post ('/login',function(req,res){for(var index = 0; function(err){res.send(' registered successfully ')})}) index < allUserArray.length ; index ++){ var user = allUserArray[index] if(user.account == req.body.account){ if(user.password == req.body.password){ res.cookie("loginName" , Req.body.account) res.send(" login failed, password error ")} else{res.send(" login failed, password error ")} return}} res.send(" login failed, account is not registered ")}) // ask questions Web.post (' question',function(req,res){// Find the same person as the one who asked the question Alluserarray. filter(function(el){return el.account == req.body.user}) var question = {// asker:req.body.user, / / questions content content: the req. Body. Question, / / questions from time to time: getTime (), / / ask the pictures the header: register[0].header , AnswerList :[]} // Put the latest question in the first place in the array allQuestionarray.unshift (question) fs.writefile ('question.txt', JSON.stringify(allQuestionArray) , Function (err){res.send(' question ',function(req,res){res.send(allQuestionArray)}) Web. post('/sendAnswer',function(req,res){var findUser = allUserArray.filter(function(el){return el.account == The req. Body. AnswerMan}) var answer = {/ / answer people answerMan: the req. Body. AnswerMan, / / answer content content: the req. Body. The content, / / time time: getTime (), // findUser[0].header} // Place the latest answer in the first place of all the answers in the specified question allQuestionArray[req.body.index].answerList.unshift(answer) fs.writeFile('question.txt' , Json.stringify (allQuestionArray),function(){res.send(" answer successful ")})}) var headerConfig = multer({storage:diskStorage}) web.post('/upload' , Headerconfig. single("photo"),function(req,res){allQuestionarray. forEach(function(el){// If the questioner and the questioner are the same person, change the profile picture if(el.asker == req.cookies.loginName){ el.header = headerName } if(el.answerList){ el.answerList.forEach(ans => { // Change your avatar if(ans. AnswerMan == req.cookies. LoginName){ans. Header = headerName}}); } }) fs.writeFile('question.txt' , Json.stringify (allQuestionArray),function(){res.send("<script>location.href='/'</script>")})}) // Get the current user profile picture web.get('/getHeader',function( req ,res){ var index = allUserArray.findIndex(function(el){ return el.account == Function getTime(){var time = new Date() function getTime(){var time = new Date() Time = time.tolocaleString () // convert/to time.replace(/\//g, '-') time = time.replace(' morning ','') time = time.replace(' afternoon ','') return time}Copy the code