最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to listen to GET requests using only http with node? No express - Stack Overflow

programmeradmin1浏览0评论

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 return 405 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
Add a ment  | 

1 Answer 1

Reset to default 10

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');
发布评论

评论列表(0)

  1. 暂无评论