Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Node.js HTTP Server Routing

Tags:

node.js

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!');
});
like image 297
Ali Avatar asked Mar 12 '19 02:03

Ali


Video Answer


1 Answers

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
});
like image 164
Rubin bhandari Avatar answered Oct 20 '22 10:10

Rubin bhandari