简体   繁体   English

如何仅使用带有节点的http来监听GET请求? 没有快递

[英]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 of express. 我想知道如何仅使用“ require http”而不是express来监听http get请求。

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. 我想听取请求,然后console.log 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. 您需要使用http:message.method检查使用了哪种方法,如果不是GET则发送另一个响应。

'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');

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM