Created
December 11, 2022 14:10
-
-
Save benixal/694c3a6cf933add8521fa7b1fd15a027 to your computer and use it in GitHub Desktop.
simple nodejs api test
This file contains hidden or 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 port = 8089; | |
| http.createServer((req, res) => { | |
| const headers = { | |
| 'Access-Control-Allow-Origin': '*', | |
| 'Access-Control-Allow-Methods': '*', | |
| 'Access-Control-Request-Method': '*', | |
| 'Access-Control-Allow-Headers': '*', | |
| }; | |
| if (req.method === 'OPTIONS') { | |
| res.writeHead(204, headers); | |
| res.end(); | |
| return; | |
| } | |
| if (['GET', 'POST', 'PUT', 'PATCH', 'DELETE'].indexOf(req.method) > -1) { | |
| res.writeHead(200, headers); | |
| console.log(req.method) | |
| console.log(req.url) | |
| var body = ""; | |
| req.on("data", function (chunk) { | |
| body += chunk; | |
| }); | |
| req.on("end", function () { | |
| try { | |
| console.log(JSON.parse(body)) | |
| } catch (e) { | |
| } | |
| }); | |
| if (req.method == 'POST') { | |
| res.end(JSON.stringify({ id: Math.floor(Math.random() * 10000), message: "added" })); | |
| } | |
| if (req.method == 'PATCH') { | |
| res.end(JSON.stringify({ message: "updated" })); | |
| } | |
| if (req.method == 'DELETE') { | |
| res.end(JSON.stringify({ message: "deleted" })); | |
| } | |
| return; | |
| } | |
| }).listen(port); | |
| console.log("api Server is ready on http://127.0.0.1:"+port); | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment