Skip to content

Instantly share code, notes, and snippets.

@picpoint
Created May 15, 2019 20:37
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save picpoint/775f2c595ee9439d5bfaf6afdca59bdb to your computer and use it in GitHub Desktop.
Save picpoint/775f2c595ee9439d5bfaf6afdca59bdb to your computer and use it in GitHub Desktop.
Server for work width POST request and save data on json format
<!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>
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