Can Node.js Applications Have Static URLs?

So, I heard a lot about Node.js and javascript web applications in general. Examples that, as I know, tend to function more like native applications than web applications in these static URLs, are not available. They do not seem to have dedicated pages that you can link to.

My question is ... are you wise to create a web application in Node.js if the presence of static pages (URLs) in it is important for this application (for example, think about how to link to a tweet or ebay list or Wordpress post).

Thanks!

Eddie

+4
source share
1 answer

This answer is for static pages and files, as static URLs are not really a problem with node.js, and it is described here in the express js guide .

Using only node.js without any structure is a pretty bad idea if you are going to create a webapp. However, there are many good webframeworks for node.js, which makes life a lot easier. If you installed NPMs , they are also very easy to enable.

I have experience with express.js , but it really makes it easier to create webapps if you have previous experience with any web framework like MVC.

In my experience, it is true that there is no way to serve static pages embedded in node.js. However, creating a controller that can serve static pages is very simple.

Here is an example using express.js.

server.js

... app.get('/content/*', controllers.content.getfile); ... 

This creates a route that captures each URL that goes to the content directory and directs it to the get action file in the content controller, for example www.yourdomain.com/content/style.css

controllers.js

 ... exports.content = { getfile : function(req,res){ var uri = url.parse(req.url).pathname; var filename = path.join(process.cwd(), uri); path.exists(filename, function(exists){ if(!exists){ res.writeHead(404, {"Content-Type" : "text/plain"}); res.write("Content not found"); res.end(); return; } fs.readFile(filename, "binary", function(err, file){ res.writeHead(200, {'Content-Type' : mime.lookup(filename) }); res.write(file, "binary"); res.end(); }); }); } } ... 

This getfile action in the content controller looks for the file specified in the URL in the content directory and serves it to the client. This requires the mime library, which you can get with NPM.

This allows you to use static files in the / content / folder. If you want you to be able to catch every caught URL and look for a static file from the up path. However, you will need to configure some kind of filter so that you cannot just access the server.js file.

+7
source

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


All Articles