This is a question and answer system, can realize the functions of registration, login, issue questions, answer questions, change the profile picture. The main purpose is to consolidate newly learned Node.js knowledge. Every new knowledge has a huge and complete system, but we must use common and important knowledge proficiently. Homepage Preview

1. Register and log in

After entering the q&A system, you can directly enter the home page for browsing. To use the q&A function, you need to register and log in firstFront-end main code

<input type="text" ID ="account" placeholder=" input account no less than 4 characters "><br> <label for="password"> Password :</label><br> <input Type ="text" ID ="password" placeholder=" input password: at least 4 characters "><br> <label for="againpasword"> </label><br> <input <br> <input type="submit" value=" registered "onclick="registered()" class="zhuce">Copy the code

Front-end main JS code

var account = document.getElementById('account').value var password = document.getElementById('password').value var againpasword = document.getElementById('againpasword').value var xhr = new XMLHttpRequest() xhr.open('post', '/registered') xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded') xhr.send(`account=${account}&password=${password}`) xhr.onreadystatechange = Function () {if (xhr.readyState == 4) {if (xhr.responseText == 'registered ') {location.href = './login.html'} else {function () {if (xhr.responseText ==' registered ') {location.href = './login.html'} else { alert(xhr.responseText) } } } }Copy the code

Data requests are made using the POST method of the XHR request. The back-end writes to the ‘/registered’ interface. Create ‘alluser. TXT ‘to store registered users.

Fs.access ('alluser.txt', (noExists) => {if (noExists) {fs.writefilesync ('alluser.txt', '[]') } else { fs.readFile('alluser.txt', 'utf-8', (err, data) => { alluser = JSON.parse(data) }) } })Copy the code
console.log(req.body); for (var index = 0; index < alluser.length; Index++) {var aluser = alluser[index] if (aluser.account == req.body.account) {console.log(' duplicate account '); Res. send(' account already exists ') return}} console.log(' account not duplicate '); Header = './header/default.jpg' alluser.push(req.body) fs.writefile ('alluser.txt', JSON. Stringify (alluser), (err) = > {res. Send (' registration ')})})Copy the code

After the user is registered, location.href=”./login. HTML “jumps to the login page

Front-end HTML code and JS code

Here again, the POST method of the XHR request is used for data requests.

<label for="password"> </label><input type="text" id="password"><br> <input type="submit" value=" "onclick=" "class="denglu">Copy the code
var account = document.getElementById('account').value var password = document.getElementById('password').value var xhr = new XMLHttpRequest() xhr.open('post', '/login') xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded') xhr.send(`account=${account}&password=${password}`) xhr.onreadystatechange = function () { if (xhr.readyState == 4) { console.log(xhr.responseText); If (xhr.responseText==' login succeeded '){location.href = "./index.html"}if(xhr.responsetext ==' login failed '){alert(' login failed ')}}}}Copy the code

The logon logic is to iterate over ‘allUser’ and assign the indexed alluser to aluservar aluser = alluser[index], Compare the account password sent from the front end with the registered account password traversed by the back end.

for (var index = 0; index < alluser.length; index++) { var aluser = alluser[index] if (aluser.account == req.body.account) { if (aluser.password == req.body.password) { res.cookie('uname', Req.body.account) res.send(' login succeeded ')} else {res.send(' password error ')} return}} res.send(' account not registered ')})Copy the code

Login successful

“I want to answer” click “I Want to Answer” if you are not logged in, you will be redirected to the login page. Click “Log in” to answer the question. Click “Answer” to bring up the input answer mode box

var content = $('textarea').val() console.log(content); If (content.length == 0) {alert(' submit without question 🀠🀠🀠') return} var XHR = new XMLHttpRequest() xhr.open('post', '/submitAnswer') xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded') xhr.send(`content=${content}&index=${$.cookie('index')}&answerMan=${$.cookie('uname')}`) xhr.onreadystatechange = function () { if (xhr.readyState == 4) { console.log(xhr.responseText); / / answer after hidden modal box $(' # myModal). Modal (' hide ') / / the content of the empty box $(' textarea). Val (' ') location. Href = ('. / index. HTML ')}}}Copy the code

Unable to submit without input content in the answer box after input content click Submit

web.post('/submitAnswer', (req, res) => { console.log(req.body); Var findUser = alluser.filter(function (el) {return el.account = req.body.answerman}) var answer = {// Answer: Header: findUser[0]. Header, // Answer the person answerMan: req.body. AnswerMan, // Answer the time: getTime(), Getallquestion [req.body.index].answerList.unshift(answer) // Then write again Fs.writefile ('getallquestion. TXT ', json.stringify (getallquestion), (err) => {res.send(' answer successful ')})})Copy the code

After successful login, you can log out and change your profile picture

Click upload avatar to submit to background via form post method ‘/upphoto’ interface

 <form action="/upphoto" method="POST" enctype="multipart/form-data">
                πŸ‘‰<label for="pho">🐷</label>πŸ‘ˆ<br>
                <input type="file" name="photo" id="pho" accept="image/*" required class="hide">
                <input type="submit" name="" id="" class="btn btn-primary" value="上传">
            </form>
            
Copy the code

Configure information and receive and upload profile pictures in the background

Var headerName = "var diskStorage = multer.diskStorage({destination: function (req, file, callback) { callback(null, './public') }, filename(req, file, callback) { var splitArray = file.originalname.split('.') var type = splitArray[splitArray.length - 1] headerName = './header/' + req.cookies.uname + '.' + type var index = alluser.findIndex(function (el) { return el.account == req.cookies.uname }) alluser[index].header = headerName fs.writeFile('alluser.txt', JSON.stringify(alluser), (err) => {}) callback(null, headerName)}}) var headerConfig = multer({storage: Web. Post ('/upphoto', headerconfig. single('photo'), (req, res) => {console.log(req.body); Getallquestion. ForEach (function (el) {if (el.askquestion == req.cookies. Uname) {el.header = headerName } if (el.answerList) { el.answerList.forEach(ans => { if (ans.answerMan == req.cookies.uname) { ans.header = headerName } }) } }) fs.writeFile('getallquestion.txt', JSON.stringify(getallquestion), (err) => { res.send("<script>location.href='/'</script>") }) })Copy the code

Click Exit login Settings exit login function to clear the login user name cookie value and refresh the page

 function recookie() {
            $.cookie('uname', '')
            location.href = './index.html'
        }
Copy the code