Created
May 15, 2019 20:37
-
-
Save picpoint/775f2c595ee9439d5bfaf6afdca59bdb to your computer and use it in GitHub Desktop.
Server for work width POST request and save data on json format
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!DOCTYPE html> | |
<html lang="en"> | |
<head> | |
<meta charset="UTF-8"> | |
<title>Title</title> | |
</head> | |
<body> | |
<form action="/" method="post"> | |
<input type="text" placeholder="Login" name="username"> | |
<input type="password" placeholder="password" name="password"> | |
<button type="submit">Sing in</button> | |
</form> | |
</body> | |
</html> |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const http = require('http'); | |
const fs = require('fs'); | |
const path = require('path'); | |
function parseBody (body) { | |
const result = {}; | |
const keyValuePairse = body.split('&'); | |
keyValuePairse.forEach(keyValue => { | |
const [key, value] = keyValue.split('='); | |
result[key] = value; | |
}); | |
return result; | |
} | |
const server = http.createServer(function (req, res) { | |
if (res.statusCode > 200) { | |
throw new Error('error to work server'); | |
} else { | |
res.writeHead(200, {'Content-Type': 'text/html'}); | |
//res.end('server is work!'); | |
switch (req.method) { | |
case 'GET': | |
const stream = fs.createReadStream(path.join(__dirname, 'public', 'form.html')); | |
res.writeHead(200, {'Content-Type': 'text/html'}); | |
stream.pipe(res); | |
break; | |
case 'POST': | |
let body = ''; | |
req.setEncoding('utf-8'); | |
req.on('data', data => body += data); | |
req.on('end', () => { | |
const data = parseBody(body); | |
res.writeHead(200, {'Content-Type': 'application/json'}); | |
res.end(JSON.stringify(data)); | |
}); | |
break; | |
} | |
} | |
}); | |
server.listen(8080, () => console.log('server is starting')); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment