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").
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").
Share Improve this question asked Dec 15, 2016 at 20:46 McFiddlyWiddlyMcFiddlyWiddly 58110 silver badges32 bronze badges 5-
Then you need to check what method was used http: message.method and if it is not
GET
then send another response. – t.niese Commented Dec 15, 2016 at 20:52 -
FYI. You'd send a
400 Bad Request
to a valid url with invalid parameters. What you should do is send a 404 instead. – manonthemat Commented Dec 15, 2016 at 20:52 - Can you give me a small example of how to use http: message.method? – McFiddlyWiddly Commented Dec 15, 2016 at 20:55
-
1
@manonthemat If a resource exists and only supports
GET
, and you send request with another method e.g,POST
, then the server should return405 Method Not Allowed
. – t.niese Commented Dec 15, 2016 at 21:00 - @t.niese true, good point. – manonthemat Commented Dec 15, 2016 at 21:13
1 Answer
Reset to default 10You 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');