Static file not serving in Node.js - node.js

I am new in programming and face static file serving problem. I followed my tutor properly but still face the problem. This is the server file named app.js from where I want to serve the js file named index.js in the static directory
const express = require('express');
const app = express();
const port = 3000;
app.use('/static' , express.static('static'));
app.get('/', (req, res)=>{
res.send('This is a page of website');
})
app.listen(3000 , ()=>{
console.log(`The application is running at port ${port}`)
})
And I made a directory named static in which I made a file index.js with some js contents.
The tutor then runs the terminal with node ./app.js and in the browser, he searches for the URL as localhost/static/index.js and he was served with the js file as a static file but for me, it shows the site can't be reached. Considering there is no issue in my node.js processing.

Actually, the problem was the URL search. As you know that for localhost if you are running the server at port 80 it does not require writing the port. But since I used port 3000 and I do not mention the port in the URL that is why it shows me the site cant be reached and my tutor was using port 80 and me 3000.

I believe the issue could be that you forgot to add the port to the URL. Your server is listening on port 3000, so you need to search for 'http://localhost:3000/static/index.js'.

one more solution is it here. If the name of the Html file inside the public folder is different from index.html so this is also not work. so first set folder name index.html and then connect your index.js folder to html file ,then run server.you are definitely gets the results .
i am also a psuedo programmer if any mistakes please forgive me.
thank you.

Related

I am trying to run a react app and an express app on the same localhost

I am writing an application and I want it to look like this
mydomain.com - react-app
api.mydomain.com - node express app
SO I created a parent folder. Inside the parent folder, i initialized npm and created my app.js file. I have also created a react app called client inside the parent folder.
I want to write my express code in the app.js file. Now I am trying to link them to run on the same port, using vhost
This is what I did in app.js
const app = express()
app.use(vhost('home.localhost', require('./client_home/src/App')))
const port = 7000
app.listen(port, () => {
console.log(`Server running on port ${port}`)
})
This doesn't run. I get some errors
How can I achieve what to want to do? Is there any best module to achieve this?

Basic express setup: not sending anything to local port

I created a frontend app and now trying to incorporate backend into it.
ON the same frontend app i added an index.js file in the root directory, and installed express and required it in index.js file.
Very basic setup as below:
const express = require('express')
const cors = require('cors')
const port = process.env.PORT || 3001
const app = express()
app.get('/', (req, res) => {
res.send({
greetings: 'hi'
})
})
app.listen(port, () => {console.log(`Server on port ${port}`)})
Server is successfully on port 3001 as per my terminal, however, on localhost:3001 I'm not seeing any json response I set up in app.get.
It says Cannot GET / instead. When i inspected in devtool(Network) it says 404.
This seems a very straightforward setup, but what could've gone wrong here?
i just figured why. I installed nodemon but my “start” script is “node index.js”. Should’ve used “nodemon index.js”
Working now with nodemon index.ks
Your code is fine, There are no errors, I tested it and it works as expected.
However few things to note, Keep Backend in Seperate folder/dirctory unless required.
Coming back to your question, There are many possiblity such as some modules are not installed properly
try running following command
//this will install if any library is currupt or not installed properly
npm i
if it doesn't work then try clearing cache
Also keep in mind, In nodeJS dev server does not automatically refresh changes, you need to restart server to see changes or you can use dev dependancy called Nodemon (this will auto restart server on saving changes)

Express server and NGINX proxy only serving index.html, no other files

I have a very simple express app which serves everything in the build folder for my react app. Here's the entire thing:
const express = require("express");
require("dotenv").config();
const app = express();
const port = process.env.PORT || 5000;
app.use(express.static(process.env.PUBLIC_DIR));
app.use(express.json());
app.listen(port, () => {
console.log(`Server is running on port ${port}...`);
});
When running this on my local machine, it works fine. No issues.
On my EC2 instance, I'm using NGINX as a reverse proxy. Here's what the config in my default sites-available file looks like:
location / {
proxy_pass http://localhost:5000/;
}
location /upvotes {
proxy_pass http://localhost:5002/;
}
When you just go to the main site, another express app on 5000 serves a totally unrelated Gatsby project. That works fine, no issues.
When you go to /upvotes, this express app on 5002 does serve the index.html file perfectly fine, but it doesn't serve any of the accompanying .js and .css files that are also in that directory.
Does anyone know why this could be happening?
I eventually gave up and combined the two express apps into one and handled the /upvotes route using express. 🤷

Error trying to render the index.html that ng build generates with node and express

I want to deploy an application that I perform with the MEAN stack on Heroku, but I encounter 1 problem.
I have this folder structure, my node server, with a public folder, where is the dist / fronted folder and all the files generated by Angular's ng build --prod, it works when I start the server and browse normally, but if I refresh the page or write a route myself, I get these errors:
Errores
Sorry for my English.
If your are building a MEAN stack, you probably have a server.js or index.js or app.js as an entry point to your application. An SPA by definition manages all the routes within the router configuration. But if you try to refresh or type a route yourself, it is like you were trying to access that folder on the server (ex: www.mywebsite.com/about, here the folder about might not exist on the server, it is just known by your Angular app)
My suggestion is that you try to add this fix to the app.js (or server.js or app.js) file, so all unexisting routes or refresh go back to your index.html:
// Check your port is correctly set:
const port = process.env.PORT || 8080;
// Is saying express to put everything on the dist folder under root directory
// Check the folder to fit your project architecture
app.use(express.static(__dirname + "/dist"));
// RegEx saying "capture all routes typen directly into the browser"
app.get(/.*/, function(req, res) {
// Because it is a SPA, all unknown routes will redirect to index.html
res.sendFile(__dirname + "/dist/index.html");
});
app.listen(port);
This guy shows full deploy on Heroku with Angular: https://www.youtube.com/watch?v=cBfcbb07Tqk
Hope it works for you!

How does express know this routing?

I create a simple express server and serve the static files
const express = require('express');
const app = express();
app.use(express.static('public'));
app.listen(3000, () => {
console.log('Listening on port 3000')
})
When I head to localhost:3000, the index.html in my public directory renders for the route ' / '. I didn't explicitly write the route in my index.js file. How does express know this?
I've tried changing the file name from index.html to random.html and I get an error. CANNOT GET /
As mentioned in the comments, app.use(express.static('public')) is responsible for this. This will essentially serve all files in the public folder you have in the project. If you have an index.html in the public folder, then that will be served at the / endpoint automatically. This is a convention that most websites follow, and is documented in this SO post.
Here is the relevant documentation on express.static(...): https://expressjs.com/en/starter/static-files.html

Resources