13

below node.js code is using express to route to different urls, how can I do the same with http instead of express?

var express = require('express');
var app = express();

app.use(express.static('public'));

app.get('/', function (req, res) {
    res.send('Welcome Home');
});

app.get('/tcs', function (req, res) {
    res.send('HI RCSer');
});


// Handle 404 - Keep this as a last route
app.use(function(req, res, next) {
    res.status(404);
    res.send('404: File Not Found');
});

app.listen(8080, function () {
    console.log('Example app listening on port 8080!');
});

4 Answers 4

17

Try the code below . It is a pretty basic example

var http = require('http');

//create a server object:

http.createServer(function (req, res) {
 res.writeHead(200, {'Content-Type': 'text/html'}); // http header
var url = req.url;
 if(url ==='/about'){
    res.write('<h1>about us page<h1>'); //write a response
    res.end(); //end the response
 }else if(url ==='/contact'){
    res.write('<h1>contact us page<h1>'); //write a response
    res.end(); //end the response
 }else{
    res.write('<h1>Hello World!<h1>'); //write a response
    res.end(); //end the response
 }
}).listen(3000, function(){
 console.log("server start at port 3000"); //the server object listens on port 3000
});
Sign up to request clarification or add additional context in comments.

Comments

14

Here's a quick example. Obviously, there are many ways of doing this, and this is probably not the most scalable and efficient way, but it will hopefully give you an idea.

const http = require('http');
const fs = require('fs');

const server = http.createServer((req, res) => {

    req.on('error', err => {
        console.error(err);
        // Handle error...
        res.statusCode = 400;
        res.end('400: Bad Request');
        return;
    });

    res.on('error', err => {
        console.error(err);
        // Handle error...
    });

    fs.readFile('./public' + req.url, (err, data) => {
        if (err) {
            if (req.url === '/' && req.method === 'GET') {
                res.end('Welcome Home');
            } else if (req.url === '/tcs' && req.method === 'GET') {
                res.end('HI RCSer');
            } else {
                res.statusCode = 404;
                res.end('404: File Not Found');
            }
        } else {
            // NOTE: The file name could be parsed to determine the
            // appropriate data type to return. This is just a quick
            // example.
            res.setHeader('Content-Type', 'application/octet-stream');
            res.end(data);
        }
    });

});

server.listen(8080, () => {
    console.log('Example app listening on port 8080!');
});

Comments

0

express can also be used by http directly. From: https://expressjs.com/en/4x/api.html#app.listen

The app returned by express() is in fact a JavaScript Function, designed to be passed to Node’s HTTP servers as a callback to handle requests.

var http = require('http')
var express = require('express')
var app = express()

http.createServer(app).listen(80)

With this, you can still make use of express for routing, while keeping native http support.

Comments

0

You will use the .url of the IncomingMessage object created by http.Server as the basis of your path matching. You want to use .startsWith instead of equality operators (===) so that query parameters are supported. For example:

const SERVER = http.createServer(async function(request, response) {
  if (request.url.startsWith('/store')){
    // handle /store?product=shoe&brand=nike&color=blue
  } else if (request.url.startsWith('/auth')){
    // handle /auth?jwt
  } else {
    // handle index or / path
  }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.