Host multiple pages on sites

So, I have an application at http://localhost:8080/

How can I http://localhost:8080/subpage ? Since this is like any page that hits: 8080 pulls out server.js

thanks!

** edit is what worked for me (thanks stewe's ) **

 var app = require('http').createServer(createServer); var fs = require('fs'); var url = require('url'); function createServer(req, res) { var path = url.parse(req.url).pathname; var fsCallback = function(error, data) { if(error) throw error; res.writeHead(200); res.write(data); res.end(); } switch(path) { case '/subpage': doc = fs.readFile(__dirname + '/subpage.html', fsCallback); break; default: doc = fs.readFile(__dirname + '/index.html', fsCallback); break; } } app.listen(8080); 
+6
source share
2 answers

Here is the start:

 var http=require('http'); var url=require('url'); var server=http.createServer(function(req,res){ var pathname=url.parse(req.url).pathname; switch(pathname){ case '/subpage': res.end('subpage'); break; default: res.end('default'); break; } }).listen(8080); 
+6
source

I ran into the same problem as you and I think we both searched, this is basically a routing mechanism for node.js. Basically, well, I get a hello-world example for nodejs, but how do I create something that answers different requests?

For future users who land on this page via google, you should look at Express.js and this is a great guide and introduction to express Understanding Express.js . These two solutions to the problem

+4
source

Source: https://habr.com/ru/post/896534/


All Articles