Search code examples
node.jsexpresshttpnpmneedle.js

Running http module in express route - NodeJS


I want to render some HTML text within my express route. I know one of the options is using the npm-needle module but I was unsure if we there is any way to use npm-express and npm-http within the same route defined.

What I want is something like:

var http = require("http");
var express = require("express");
var app = express();

app.get("/", function (req, res) {
  var params = req.params;
  var url = req.query["url"];
  let handleRequest = (request, response) => {
    response.writeHead(200, {
      "Content-Type": "text/plain",
    });
    response.write("Hi There! " + url);
    response.end();
  };
});
app.listen(5000);
//http.createServer(handleRequest).listen(8000); ---> not using this in the code

Is something of this type possible? Thanks!


Solution

  • I don't get why you do have this handleRequest function inside your route as you can use the req and resinside of this function inside your route.

    If you want to deliver html from within your route you could send back a html file like this:

    const path = require('path');
    
    app.get("/", function (req, res) {
        res.sendFile(path.join(__dirname + '/index.html'));
    });
    

    or you could send back directly html-tags from within your route like this:

    app.get("/", function (req, res) {
        res.send('<h1>Text</h1>')
    });
    

    Of course you can work with template strings etc. to get your data displayed.