Created
February 18, 2020 18:38
-
-
Save FlyInk13/57f1bd100cbeaa86fa8e8273fb627716 to your computer and use it in GitHub Desktop.
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 url = require('url'); | |
const http = require('http'); | |
function getBody(req, res) { | |
return new Promise(function inPromise(resolve, reject) { | |
if (req.method !== "POST") { | |
resolve(); | |
} | |
res.body = ''; | |
req.on("data", (b) => { | |
res.body += b; | |
}); | |
req.on("end", () => { | |
resolve(res.body); | |
}); | |
req.on("error", reject); | |
}).then((body) => { | |
return body ? JSON.parse(body) : {}; | |
}); | |
} | |
http.createServer((req, res) => { | |
req.urlData = url.parse(req.url, true); | |
Promise.resolve().then(() => { | |
return getBody(req, res).then((body) => { | |
const act = req.urlData.pathname; | |
Object.assign(body, req.urlData.query); | |
if (API.hasOwnProperty(act)) { | |
return API[act](req, res, body); | |
} else { | |
return API.default(req, res, body); | |
} | |
}); | |
}).catch((e) => { | |
console.error('catch', e); | |
res.end(JSON.stringify({ | |
error: e.error_msg || "Неизвестная ошибка", | |
code: e.error_code || 500 | |
})); | |
}); | |
}).listen(8081); | |
const API = { | |
'/echo': (req, res, body) => { | |
res.writeHead(200, { | |
'Content-Type': 'text/json; charset=utf-8', | |
'Access-Control-Allow-Origin': '*', | |
}); | |
res.end(body.input || 'empty input'); | |
}, | |
default: (req, res, body) => { | |
console.log('pathname:', req.urlData.pathname); | |
res.end('default'); | |
} | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment