Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to listen to GET requests using only http with node? No express

I'm wondering how to listen to http get requests with only "require http" instead o f express.

This is what I have now:

let http = require('http');
let server = http.createServer(function (req, res) {
    res.writeHead(200, {'Content-Type': 'text/plain'});
    res.end('Hello, World!\n');
});
server.listen(8443);
console.log('Server running on port 8443');

I want to listen to get requests, and console.log the url. and if there is any other request i want to print ("bad request").

like image 451
McFiddlyWiddly Avatar asked Apr 18 '26 18:04

McFiddlyWiddly


1 Answers

You need to check what method was used using http: message.method and if it is not GET then send another response.

'use strict'
let http = require('http');
let server = http.createServer(function (req, res) {
  if( req.method === 'GET' ) {
    res.writeHead(200, {'Content-Type': 'text/plain'});
    res.end('Hello, World!\n');
  } else {
    res.writeHead(405, {'Content-Type': 'text/plain'});
    res.end('Method Not Allowed\n');
  }
});
server.listen(8443);
console.log('Server running on port 8443');
like image 115
t.niese Avatar answered Apr 21 '26 06:04

t.niese