+ 1

How to handle POST request on my http server in js? Allready answered

I'm not sure how to explain it, but when I send a POST request to the server nothing happens. I'm missing the code on the server to handle the request. I am only interested in http module (because I want to understand it before I move on to Express) What to do from here? My request: fetch('http://127.0.0.1:5674', { method: 'POST', body: ' Anton', headers: {"content-type": "text/plain"} }) .then(response => console.log(response)) .catch(err => { console.log('failed', err) }) My server let http = require('http'); const server = http.createServer((req, res) => { if (req.method === 'POST'){ res.writeHead(200, { 'Content-Type': 'text/plain' }); res.end(req.body); } if (req.url === '/') { res.writeHead(200, { 'Content-Type': 'text/plain' }); res.end('hello'); } else { res.writeHead(404, { 'Content-Type': 'text/plain' }); res.end('404 Not Found'); } }); server.listen(5674, '127.0.0.1', () => { console.log('Server is running') })

12th Jul 2023, 10:40 AM
Anton Drud
Anton Drud - avatar
5 Respuestas
+ 2
There's a lot to explain here .. let me save me some stress The condition for checking for POST should be under a specific url path, for example if (req.url == "/submit") { if (req.method == "POST") { // Do something } } This will solve 90% of the problem . You can't just have that condition like that without specificying a path that requires POST request. also, try to fetch from the frontend after clicking a button not at the top level of your server code.. it seems unreal doing it that way
12th Jul 2023, 9:59 PM
RuntimeTerror
RuntimeTerror - avatar
+ 1
I think you should take a look at this, and then concentrate on Express instead. It shows exactly how you handle a POST request. https://codeforgeek.com/handle-get-post-request-express-4/
12th Jul 2023, 1:30 PM
Jan
Jan - avatar
+ 1
Thanks, but i want to know how to do it in http module before moving on to Express.
12th Jul 2023, 3:59 PM
Anton Drud
Anton Drud - avatar
+ 1
Quantum are you danish?
12th Jul 2023, 4:02 PM
Anton Drud
Anton Drud - avatar
+ 1
Yes, I am.
12th Jul 2023, 6:31 PM
Jan
Jan - avatar