Node.js & express.js preview in VSCode - javascript

So I'm learning backend and I'm doing a simple express.js experiment. I'm using a simple GET HTTP Protocol to preview an HTML (index.html). I'm working in replit.com and I could see the preview of the index.html file that is created:
I could also get a JSON respond from a code that I've wrote if I go to link my-replit-link.co/json. This is the javascript code that I've wrote to preview the index.html and preview json on '/json' using express.js:
let express = require('express');
let app = express();
app.use('/public', express.static(__dirname + '/public'));
app.get('/', function (req, res) {
res.sendFile(__dirname + "/views/index.html");
})
app.get('/json', function (req, res) {
res.json({
"message": "Hello json"
})
module.exports = app;
But I'm trying to do it also in VSCode. Is there any way I could preview like in replit.com using VSCode?
Any helpful answer would be very appreciated, thanks!

Related

Will node js compile javascript code which is saved in other extensions?

so, today when i'm going to save my javascript code, i've saved it with other extension, and the code is compiled successfully
//server.mp3
var express = require('express');
var app = express();
app.get("/", function (req, res) {
res.sendFile(__dirname + '/index.html')
})
app.listen(3000, function () {
console.log("Listening at 3000")
});
when i said :
node server.mp3
my server is running on port 3000...
how it is possible?
Node.js doesn't do different things depending on what type of file you open with it. It therefore doesn't try to determine what type of file you have given it based on the file extension. It just tries to execute it as JS.

Loading HTML files in Nodejs

I am trying to load HTML files in nodejs. In public folder, I have two html files test.html and index.html. I would like to use nodejs to showcase the pages, but its working for index.html and for the case of test, it shows an error saying that res.sendFile is not a function.
var express = require('express');
var app = express();
var path = require('path');
// viewed at http://localhost:8080
app.get('/', function(req, res) {
res.sendFile(path.join(__dirname + '/public/index.html'));
});
// viewed at http://localhost:8080
app.get('/test', function(req, res) {
res.sendFile(path.join(__dirname + '/public/test.html'));
});
app.listen(8080);
For serving static files such as JS, CSS, images, html files, you can use the express.static built-in middleware function in Express.
Serving static files in Express
Say if your 'Public' folder has some JS, html files which is required at client side. Then you need do to go like this :-
var express = require('express');
var app = express();
app.use(express.static(__dirname + '/public'));
var server = app.listen(8080);

Node JS - HTML Paths

I recently have the problem that I dont get how the paths for html in node js work. I link my index.html's scripts as normal - relative to the index.html's file (node.js file and index.html are in the same directory "res.sendFile(__dirname + '/index.html');"). But if I open it up in the Browser executed with node js it just stats "cant GET blabla" for the scripts. Instead opening it up by just clicking index.html without node js those paths work! How do I have to write html paths for node js?
var express = require('express'),
app = express(),
server = require('http').createServer(app),
io = require('socket.io').listen(server),
port = Number(process.env.PORT || 3000),
server.listen(port);
app.get('/', function(req, res){
res.sendFile(__dirname + '/index.html');
});
Thanks for your time! :)
Look at this:
app.get('/', function(req, res){
res.sendFile(__dirname + '/index.html');
});
You have told Node "When the browser asks for / give it index.html".
What happens when the browser asks for someScript.js?
You haven't told Node what to do then.
(You'll probably want to find a library for serving up static files rather than explicitly handling each one individually).
you should configure express to server static files, for example, put all the static files under a directory called 'public'
var express = require('express');
var app = express();
var path = require('path');
// viewed at http://localhost:8080
app.get('/', function(req, res) {
res.sendFile(path.join(__dirname + '/index.html'));
});
app.listen(8080);
ExpressJS to Deliver HTML Files
Render HTML file in ExpressJS
You can use
app.use(express.static(path.join(__dirname, "folder-name")));
Usually i put all my static files in a separate folder named "assets"
The I set up a static route as shown below:enter code here
app.use('/assets', express.static('assets'));
When you write:
app.get('/', function(req, res){
res.sendFile(__dirname + '/index.html');
});
It will only serve index.html file, not the other js scripts and stylesheets which you have added in your html.
There are 2 ways to solve that:
For both of them, I would suggest to use 'path' module.
Solution 1:
var path = require('path')
app.get('/path/to/js/foo.js',function(req,res){
res.sendFile(path.resolve(__dirname,'/path/to/js/foo.js')
})
app.get('/path/to/css/bar.css',function(req,res){
res.sendFile(path.resolve(__dirname,'/path/to/css/bar.css'))
})
and so on for every .css and.js file you have added in your index.html.
Solution 2:
You can create a public dir in your project's root dir. Inside which all your img, css and js files will be there.
Next,
var path = require('path')
app.use(express.static('public'))
app.get('/',function(req,res){
res.sendFile(path.resolve(__dirname,'/index.html')
})

How can I serve my web app with Node/Express?

I'm probably going to ask a huge noob question, one of the worst I've ever had asked here, but I'm lost as hell with Node/Express. I've only used Apache servers (typical WAMP/XAMP for testing purposes), so I have absolutely no idea on what I have to do to serve my web app.
My folder tree is the following:
www
nodeserver.js
(more things)
Liteconomy (my web app)
js
css
plugins
templates
index.html
sublime_project
Pretty typical, huh? Well, I've been searching how to serve this app with a simple access like localhost:8080/Liteconomy, or localhost:8080/Liteconomy.html. After that, my angular routing would do the rest, but I just can't serve the app.
I've got this written in nodeserver.js:
var express = require('express');
var app = express();
app.get('/', function (req, res) {
res.send('Hello World!');
});
app.listen(8080, function () {
console.log('Example app listening on port 8080!');
});
app.get('/Liteconomy', function (req, res) {
res.send('Liteconomy/index.html');
});
When I execute it and access to localhost:8080, I get the "Hello world", but when I go to localhost:8080/Liteconomy, I get the following plain text: "Liteconomy/index.html". If I try to access to the index resource directly, I get a "Cannot GET /Liteconomy/index.html" error.
I also tried using the static thingy, but didn't work either.
What am I doing wrong here? I guess I'm just missing something very important.
Do the following, it will resolve your issue.
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var app = express();
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
// uncomment following if you want to access your app from /liteconomy
//app.use('/liteconomy', express.static(__dirname + '/Liteconomy', {index: "index.html"}));
//This will enable you to access it form '/'
app.use('/', express.static(__dirname + '/Liteconomy', {index: "index.html"}));
// Rest of the stuff
Then if you will visit your URL that you set and port, you'll be able to access.
Using express.static is recommended way of serving static content.
Hope it helps!
You get a plain text answer because you actually ask to do it with the :
app.get('/Liteconomy', function (req, res) {
res.send('Liteconomy/index.html');
});
If you want to send a simple html file like your index.html file, you should use the "sendfile " function :
app.get('/Liteconomy', function (req, res) {
res.sendfile(__dirname + '/Liteconomy/index.html');
});
"__dirname" represents your root directory path and then you simply put your file path.
Hope that helps !
PS : by default express come with jade and ejs template support instead of just using html. I would advise you to take a look at one of them, it can be a great help to construct your application web pages.

Nodejs on single page

I'm new on Nodejs.
I have to do a web app with node js, express, socket.io on an existing website.
I use JXcore on Parallels Plesk panel to execute node.
But when I run js file and I visit any page on the website it returns "Cannot GET ".
If I use express get() function:
var app = require('express')();
var http = require('http').Server(app);
var path = require('path');
app.get('/path/to/index.html', function(req, res){
res.sendfile( path.resolve(__dirname + '/index.html') );
});
http.listen(10500, function(){
console.log('listening on *:10500');
});
it works on /path/to/index.html but every other website page is blocked by the same error "Cannot GET ".
Is there a way to run node only on one page?
Thanks
What your code is doing is defining just one route /path/to/index.html and mapping that to your index.html file. If you want to serve files from a directory, static html/css/js/whatever files, you can use the static method express provides:
app.use("/", express.static(__dirname + '/myHtmlDirectory'));
Change the "myHtmlDirectory" to whatever directory you store your files in and make sure to change the includes to define express:
var express = require('express');
var app = express();
However, if you want all GET requests to point to one single file, index.html for example, you can use the following:
app.get('*', function (req, res) {
res.sendfile( path.resolve(__dirname + '/index.html') );
});

Categories