I'm wondering how to listen to http get requests with only "require http" instead of 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").
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');
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.