npm live-server not auto-reloading - node.js

I have tried to work on the live server, installed a node package called live-server by using this command: npm install -g live-server
It worked fine, installed successfully and run live-server by live-server command.
Whenever I change my code and save on code editor, the browser won't refresh automatically.
Here is my package.json file:
"name": "nodejs",
"version": "1.0.0",
"description": "",
"main": "app.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "Abul Khoyer",
"license": "ISC"
}

I had the same problem as you and managed to get it working by making sure that the .html-file was properly formatted. I.e. like this:
<!DOCTYPE html>
<html>
<body>
<h1>Script tester!</h1>
<script type="text/javascript" src="script.js"></script>
</body>
</html>

You need to add this code:
for
Usage from node
Example:
var liveServer = require("live-server");
var params = {
port: 8181, // Set the server port. Defaults to 8080.
host: "0.0.0.0", // Set the address to bind to. Defaults to 0.0.0.0 or process.env.IP.
root: "/public", // Set root directory that's being served. Defaults to cwd.
open: false, // When false, it won't load your browser by default.
ignore: 'scss,my/templates', // comma-separated string for paths to ignore
file: "index.html", // When set, serve this file for every 404 (useful for single-page applications)
wait: 1000, // Waits for all changes, before reloading. Defaults to 0 sec.
mount: [['/components', './node_modules']], // Mount a directory to a route.
logLevel: 2, // 0 = errors only, 1 = some, 2 = lots
middleware: [function(req, res, next) { next(); }] // Takes an array of Connect-compatible middleware that are injected into the server middleware stack
};
liveServer.start(params);
Or else you can add a file .live-server.json :
If that exists it will be loaded and used as default options for live-server on the command line.
For more details see: https://www.npmjs.com/package/live-server

Use NPM To Install A Package Called PM2.
NPM is a package manager that you will use to install frameworks and libraries to use with your Node.js applications. NPM was installed with Node.js. PM2 is a sweet little tool that is going to solve two problems for you:
It is going to keep your site up by restarting the application if it crashes. These crashes should NOT happen, but it is good know that PM2 has your back. (Some people may be aware of Forever.js, another tool that is used to keep node based sites running - I think you will find that PM2 has a lot to offer.)
It is going to help you by restarting your node application as a service every time you restart the server. Some of use know of other ways to do this, but pm2 makes it easier, and it has some added flexibility.
Install PM2 by typing thr following at the command line:
sudo npm install pm2 -g
You can follow this line to setup Nodejs production environment:
https://www.digitalocean.com/community/tutorials/how-to-use-pm2-to-setup-a-node-js-production-environment-on-an-ubuntu-vps

If you're working on Windows 10 like myself, it's likely that your directory name is too long like this:
C:\Users\Del\Documents\Web Development Works\JS
Exercises[books]\Learning JavaScript\lj
Just try to move your directory to Desktop so it will be much shorter like this:
C:\Users\Del\Desktop\lj
In my case, the auto-reload of live-server is working after I move my directory to Desktop

Check your script tag in html file.
don't close your tag as empty element like this < /> .
This was preventing my browser to load page automatically.
close it properly <> .

I had the same problem as you, I solve that with check two items :
First, check your script tag in your HTML file !
<script type="text/javascript" src="script.js"></script>
if you try first step and it dosen't work again, move(copy/cut) your project's file in "DESKTOP", close Browser, VScode work space (command+K+F) and VScode (command+Q), and try again !

Related

Rendering html on npm start

I have created one project which has index.html and script.js file. So i have done npm init -y to get package.json. If i explicitly double click the index.html file it is opening it normally and functions as i want but if i do with express as res.sendFile(path.join(__dirname, './index.html')); it is not functioning properly. So i want to write an start script in a such way that it should directly run index.html
i have tried this
router.get('/',function(req,res){
res.sendFile(path.join(__dirname+'/index.html'));
})
But is is not functioning well. It is just rendering raw html in normal function it is asking me for permission to access camera and microphone. But here it asking nothing.
{
"name": "demo",
"version": "1.0.0",
"description": "VideoCall App",
"main": "index.html",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "AkshayK",
"license": "MIT"
}
I want to render index.html when i do npm start.
I have made one application with this same functionality for you. You
can check it here. https://github.com/RajatKaushik/Camera-App
Express is Middleware for handling http requests, you will have to make a GET request from the browser. Once you make the request your express app will match the path and will respond back with the file(index.html) in your case.
So, If you want to deliver the index.html file on the browser, do the following steps:-
Run your node application using node [YOUR_FILE_NAME.js] (node script.js).
If your express server is running on port 4200, then make the request to
localhost:4200/
As that's the path that you have for responding back with the index.html file.
I think the reason why your Camera and Microphone is not working is because the code that initiate that is in some script file that you have include in your HTML file as <script src="index.js"> but you are not delivering that file using express.
You can use the following code snippet to deliver that static files needed.
app.use(express.static('__dirname' + '/public'), () => {
console.log('Request Recived');
});
where the public is the folder in which your index.js file is present.
I have made one application with this same functionality for you. You
can check it here. https://github.com/RajatKaushik/Camera-App

What is the difference between nodemon and live-server?

Can someone help me understand the difference between npm packages nodemon and live-server as they both reload the server and listen for changes?
They serve two different purposes.
Nodemon will restart a Node application when file changes in a directory are detected.
Live-server on the other hand, will refresh your browser when changes are detected to any supported file types (e.g. HTML, JS, CSS). It also enables Ajax requests when you are working locally — these don't normally work with the file:// protocol.
Nodemon
To see this in action, let's create a simple Node server.
First, create a my-app directory, change into it, create a package.json file and a file named server.js. On a 'nix system, like so:
mkdir my-app
cd my-app
npm init -y
touch server.js
Then in server.js add:
const http = require('http');
const server = http.createServer(function (request, response) {
response.writeHead(200, {"Content-Type": "text/plain"});
response.end("Hello, World!\n");
});
server.listen(8000);
console.log("Server running at http://127.0.0.1:8000/");
Now, if you run node server.js, and visit http://127.0.0.1:8000/ in your browser, you will see a "Hello, World!" message.
If you edit server.js, for example to change the message to "Goodbye, World!", then refresh your browser, you will still see the ooriginal "Hello, World!" message.
To see the changes, you have to stop the application (with Ctrl + C), then restart it (with node server.js), then refresh your browser.
What nodemon does, is to wrap your Node application to automate this step of manually stopping and restarting the application.
Install it as a dev dependency:
npm i -D nodemon
And start your application like so:
./node_modules/.bin/nodemon server.js
Now when you make changes to server.js, nodemon will detect this automatically, meaning that all you need to is refresh your browser to see them — you avoid the stop/starting of the application.
Live-server
What live-server does on the other hand is quite different. You should install it globally:
npm install -g live-server
then when you start it in a directory, it will attempt to serve up an index.html file if one exists (otherwise it will display the directory's contents).
Staying in the my-app directory, create an index.html file:
touch index.html
Then add the following content:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<title>Test</title>
<style></style>
</head>
<body>
<p>Hello, World!</p>
<script></script>
</body>
</html>
Start live-server, by entering live-server in a terminal window and http://127.0.0.1:8080 should open in your browser.
Now try changing the message in the HTML file, or adding some styles or some JavaScript. When you make any of these changes and save, the browser will refresh and you will see these changes in your page.
This in itself is very practical, but nothing you couldn't do by refreshing the browser manually. Where a package like this becomes indispensable is when you make an Ajax request, include a file without using a protocol, or do anything else that would be blocked by the browser's security policy if you were to open an HTML file directly.

Node.js applies the changes only after restart

I am very new to server side scripting. And I am using NodeJS. My Problem is that after adding some new features to the app, i.e. after changing the code, these changes will be applied only after restarting the server. Till then NodeJS behaves so as though I hadn't changed anything. So for instance if I add console.log("works") and don't restart the server, then it hasn't any effect.
I am using Nuxt.js, which is actually the Vue.js framework but with additional and very usefull features mainly for server side rendering. I didn't integrate the express.js at the beginning of the project, beacause it wasn't planned to write any server side code. So I am normally exporting express and using it, which is pretty fine for me, since I need just a couple lines of code to use the NodeJS file system.
So, as it is pretty hard to code, if I should restart the server once I changed anything, I want to ask you if there is any solution to this problem.
Use nodemon
step 1 : npm install -g nodemon <- this will install nodemon globaly in your system
step 2 : change your start script within package.json
"scripts": {
"start": "nodemon fileName" <- like this //filename is you root file which starts the app like app.js
}
step 3 : npm start
This is already build in into nuxt. You just need to run it in dev mode, not in production.
E.g. for dev with change monitoring
nuxt
For production without monitoring
nuxt start
So in this particular case the following changes to the "scripts" in package.json have solved my problem.
"scripts": {
"dev": "nodemon --watch api --exec \"nuxt\"",
"start": "nodemon nuxt",
}
The following link could also be usefull to you.
Install nodemmon in your application to allow live update npm -g install nodemon
and add the following codes inside your packages json file :
"main": "app.js",
"scripts": {
"start": "node app"
},
on your command line, just type : start

proxy not working for react and node

I'm having issues with the proxy I set up.
This is my root package.json file:
"scripts": {
"client": "cd client && yarn dev-server",
"server": "nodemon server.js",
"dev": "concurrently --kill-others-on-fail \"yarn server\" \"yarn client\""
}
My client package.json file:
"scripts": {
"serve": "live-server public/",
"build": "webpack",
"dev-server": "webpack-dev-server"
},
"proxy": "http://localhost:5000/"
I've set up express on my server side to run on port 5000. Whenever I make a request to the server, ie :
callApi = async () => {
const response = await fetch('/api/hello');
const body = await response.json();
// ... more stuff
}
The request always goes to
Can someone point out what i have to do to fix this issue so that the request actually goes to port 5000?
I experienced this issue quite a few times, and I figured it's because of the cache. To solve the issue, do the following
Edit: #mkoe said that he was able to solve this issue simply by deleting the package-lock.json file, and restarting the app, so give that a try first. If that doesn't resolve it, then do the following.
Stop your React app
Delete package-lock.json file and the node_modules directory by doing rm -r package-lock.json node_modules in the app directory.
Then do npm install in the app directory.
Hopefully this fixed your proxy issue.
The reason the react application is still pointing at localhost:8080 is because of cache. To clear it , follow the steps below.
Delete package-lock.json and node_modules in React app
Turn off React Terminal and npm install all dependencies again on React App
Turn back on React App and the proxy should now be working
This problem has been haunting me for a long time; but if you follow the steps above it should get your React application pointing at the server correctly.
This is how I achieved the proxy calls.
Do not rely on the browser's network tab. Put consoles in your server controllers to really check whether the call is being made or not. For me I was able to see logs at the server-side. My node server is running on 5000 and client is running on 3000.
Network tab -
Server logs -
Check if your server is really running on the same path /api/hello through postman or browser. For me it was /api/user/register and I was trying to hit /api/user
Use cors package to disable cross-origin access issues.
Is your client being loaded from http://localhost:8080?
By default the fetch api, when used without an absolute URL, will mirror the host of the client page (that is, the hostname and port). So calling fetch('/api/hello'); from a page running at http://localhost:8080 will cause the fetch api to infer that you want the request to be made to the absolute url of http://localhost:8080/api/hello.
You will need to specify an absolute URL if you want to change the port like that. In your case that would be fetch('http://localhost:5000/api/hello');, although you probably want to dynamically build it since eventually you won't be running on localhost for production.
For me "proxy" = "http://localhost:5000 did not work because I was listening on 0.0.0.0 changing it to "proxy" = "http://0.0.0.0:5000 did work.
Make sure you put it on package.json in client side (react) instead of on package.json in server-side(node).
This solution worked for me, specially if you're using webpack.
Go to your webpack.config.js > devServer > add the below
proxy: {
      '/api': 'http://localhost:3000/',
},
This should work out.
Read more about webpack devSever proxy: https://webpack.js.org/configuration/dev-server/#devserver-proxy
I have tried to solve this problem by using so many solutions but nothing worked for me. After a lot of research, I have found this solution which is given below that solved my proxy issues and helped me to connect my frontend with my node server. Those steps are,
killed all the terminals so that I can stop frontend and backend servers both.
Installed Cors on My Node server.js file.
npm install cors
And added these lines into server.js file
var cors = require('cors')
app.use(cors())
Into package.json file of frontend or client folder, I added this line,
"proxy" : "http://127.0.0.1:my_servers_port_address_"
Now everything working fine.
Yours might not be the case but I was having a problem because my server was running on localhost 5500 while I proxied it to 5000.
I changed my package.json file to change that to 5500 and used this script:
npm config set proxy http://proxy.company.com:8080
npm config set https-proxy http://proxy.company.com:8080
I am pretty sure just changing it on the package.json worked but I just wanted to let you know what I did.
you should set the proxy address to your backend server, not react client address.
you should restart the client after changing package.json
you should use fetch('/api/...') (instead of fetch('http://localhost:8080/api/'))
Make sure you check your .env variables too if you use them. It's because of that if I was looking for a solution on that page.
I tried all the solutions, proposed here, but it didn't work. Then I found out, that I tried to fetch from root directory (i.e. fetch('/')) and it's not correct for some reason. Using fetch('/something') helped me.
Your backend data or files and react build files should be inside the same server folder.
you must give proxy after the name.{"name":"Project Name", "proxy":"http://localhost:5000"}
port should match with your backend's port.
If you are seeing your static react app HTML page being served rather than 404 for paths you want to proxy, see this related question and answer:
https://stackoverflow.com/a/51051360/345648
(This doesn't answer the original question, but searching Google for that question took me here so maybe this will help others like me.)
In my specific case, I had a both Node backend, and an inner folder with a React project. I tried #Harshit's answer, which didn't work, until I had two package.json files in my project, one in the outer folder, and one in my client (React) folder. I needed to set up the proxy in the inner package.json, and I needed to clear the cache in the inner folder.
I was having this issue for hours, and I'm sure some of the things above could be the cause in some other cases. However, in my case, I am using Vite and I had been trying to add my proxy to the package.json file, whereas it should be added to the vite.config.js file. You can click here to read about it in Vite's docs.
In the end, my code looks like this:
export default defineConfig({
server: {
proxy: {
"/api": {
target: "http://localhost:8000",
secure: false,
},
},
},
plugins: [react()],
});
My problem was actually the "localhost" part in the proxy route. My computer does not recognize "localhost", so I swapped it with http://127.0.0.1:<PORT_HERE> instead of http://localhost:<PORT_HERE>.
Something like this:
app.use('/', proxy(
'http://localhost:3000', // replace this with 'http://127.0.0.1:3000'
{ proxyReqPathResolver: (req) => `http://localhost:3000${req.url}` }
));`
For me, I solved this by just stopping both the servers i.e. frontend and backend, and restarting them back again.
Here is an opinion
Don't use proxies, use fetch directly
not working
fetch("/signup", {
method:"post",
headers:{
"Content-Type":"application/json"
},
body:JSON.stringify(
{
name:"",
email:"",
password:"",
}
)
Actually worked after wasting 6hours
fetch("http://localhost:5000/signup", { // https -> http
// fetch("/signup", {
method:"post",
headers:{
"Content-Type":"application/json" },
body:JSON.stringify(
{
name:"",
email:"",
password:"",
}
)
In my case the problem was that the proxy suddenly stopped to work.
after investigating I found that I've moved the setupProxy from the src folder and that cause the problem.
Moving it back to the src folder have solved the problem.
The problematic structure:
The solution:
faced similar issue. my proxy was not connecting restarting the react app fixed my issue
In my case it was because of typo. I wrote "Content-type": "application/json", (with small t) instead of "Content-Type": "application/json",
you should install this package:
npm install http-proxy-middleware --save
refrense: this link
Make sure your end point match with the backend.

Auto reloading a Sails.js app on code changes?

Currently is seems that for any code change in a sails.js app you have to manually stop the sails server and run sails lift again before you can see the changes.
I was wondering if there is any way when running in development mode to automatically restart the sails server when it detects a code change?
You have to use a watcher like forever, nodemon, or something else...
Example
Install forever by running:
sudo npm install -g forever
Run it:
forever -w start app.js
To avoid infinite restart because Sails writes into .tmp folder, you can create a .foreverignore file into your project directory and put this content inside:
**/.tmp/**
**/views/**
**/assets/**
See the issue on GitHub:
Forever restarting because of /.tmp.
You can use sails-hook-autoreload
Just lift your app as normal, and when you add / change / remove a model or controller file, all controllers and models will be reloaded without having to lower / relift the app.
For example with nodemon to watch api and config directories
.nodemonignore contents
views/*
.tmp/*
.git/*
Run the command after creating .nodemonignore
$> nodemon -w api -w config
Example for supervisor to ignore 3 directories
$> supervisor -i .tmp,.git,views app.js
If you're using Sails 0.11, you can install this hook to automatically reload when you change models or controllers (views do not require reloading):
npm install sails-hook-autoreload
https://www.npmjs.com/package/sails-hook-autoreload
install nodemon globally or locally.
npm install nodemon --save
npm install nodemon -g
install sails locally in you project as follows
npm install sails --save
then change package.json
from
"scripts": {
"debug": "node debug app.js",
"start": "node app.js"
},
to
"scripts": {
"debug": "node debug app.js",
"start": "node app.js",
"dev": "export NODE_ENV=development && nodemon --ignore 'tmp/*' app.js && exit 0"
},
then
npm run dev
I had the same problem and I have solved it using grunt-watch and grunt-forever with sails#beta tasks. The result is 4 grunt commands:
UPDATE: tasks are available in the current sails version (it's no longer beta :>)
start Starts the server
stop Stops the server
restart Restarts the server
startWatch Starts the server and waits for changes to restart it (using grunt-watch). This is probably your solution, but the other commands are also useful.
Here's the code - I'm using sails#beta, which includes a tasks directory, I don't know if this is included in previous versions:
First of all you have to install forever in your sails directory:
npm install grunt-forever --save-dev
tasks/config/forever.js Configure forever task.
module.exports = function(grunt) {
grunt.config.set('forever', {
server: {
options: {
index: 'app.js',
logDir: 'logs'
}
}
});
grunt.loadNpmTasks('grunt-forever');
};
tasks/config/watch.js (edit) Edit watch task in order to add a new rule
// api and assets default rules
,
server: {
// Server files to watch:
files: [
'api/**/*',
'config/**/*'
],
// Restart server
tasks: ['forever:server:restart']
}
tasks/register/watchForever.js Register your custom tasks (this file can be renamed to whatever you want)
module.exports = function(grunt) {
// Starts server
grunt.registerTask('start', [
'compileAssets',
'linkAssetsBuild',
'clean:build',
'copy:build',
'forever:server:start'
]);
// Restarts the server (if necessary) and waits for changes
grunt.registerTask('startWatch', [
'restart',
'watch:server'
]);
// Restarts server
grunt.registerTask('restart', [
'forever:server:restart'
]);
// Stops server
grunt.registerTask('stop', [
'forever:server:stop'
]);
};
With this you should be able to use
grunt startWatch
and make your server wait for changes to be restarted :>
Hope this helped!
Better you use
npm install -g nodemon
i am using this, and it will helps to improve my developing speed. no need to edit any files for this one!.
after installation
nodemon app.js
For anyone coming to this question now, it seems that this is no longer necessary - an application launched with sails lift will have a grunt watch task running, and code changes will be visible without a restart.
I didn't realise this was happening at first because there's nothing to indicate what's happening in the console, but it does seem to work without a restart (I'm using Sails 0.11)

Resources