Use of express.static middleware - node.js

Both below codes serve index.html at localhost:3000/ when the server is started.
Use of express.static
const path = require('path');
const express = require('express');
const PORT = process.env.port || 3000;
const publicPath = path.join(__dirname, '../public');
var app = express();
app.use(express.static(publicPath));
app.listen(PORT, () => {
console.log(`Server is running on port ${PORT}`);
})
Use of app.get
const path = require('path');
const express = require('express');
const PORT = process.env.port || 3000;
const publicPath = path.join(__dirname, '../public');
var app = express();
app.get('/',(req,res) => {
res.sendFile(publicPath + '/index.html');
})
app.listen(PORT, () => {
console.log(`Server is running on port ${PORT}`);
})
So why someone would choose express.static over app.get to serve static html file. What's the use of static middle ware on express

The code that doesn't use express.static will fail when serving any other static page that isn't index.html, even if index.html included other static files(as a css) it would fail.

Related

find the error while deploying the node.js app to server

I found the error while deploying the node app on the server. the index.js file code
const connectToDb = require("./DBconfig");
const express = require('express')
const router = express.Router();
var cors = require('cors');
connectToDb();
const app = express();
const port = process.env.PORT | 5000;
app.use(cors());
app.use(express.json());
connectToDb();
app.use( '/api/user' ,require('./routes/user') );
app.use( '/api/post' ,require('./routes/post') );
app.get('/', (req, res) => {
res.send('The site is start now')
})
if(process.env.NODE_ENV === "production"){
app.use(express.static("client/build"));
const path = require("path");
app.get("*",(req,res)=>{
res.sendFile(path.resolve(__dirname,'client','build','index.html'))
})
}
app.listen(port, () => {
console.log(`Example app listening on port ${port}`)
})
when I deploy the app and install the node in the server like how I install the node in server I attached the picture in which I show the installation of the node. and above I add the index.js code. It works properly in the local machine but if I hit the URL of backend backendURL it show the service unavailable error message kindly give me the solution to solve this problem.

Why my static HTML file not serving in Express.js

I don't know why my static html files are not serving in express.js when I click on about it not serving about.html but instead only plain text about which i written in res.end('about')
don't know what is the issue.
app.js
const express = require('express');
const app = express();
const port = process.env.PORT || 80;
const path = require('path');
const static_path = path.join(__dirname,"../public");
app.use(express.static (static_path));
console.log(static_path)
app.get('/',(req,res)=>{
res.send('index')
})
app.get("/about", (req,res)=>{
res.send("about")
});
app.get('*',(req,res)=>{
res.status(404).send("404 page is not found")
})
app.listen(port, ()=>{
console.log(`this website is running on ${port}`)
})
use res.sendFile() instead of res.send()
https://expressjs.com/en/api.html#res

Use of express-basic auth to simple prompt authentication in react app

I'm trying to make a simple prompt authentication for my react app and I've this file server.js:
const express = require('express');
const path = require('path');
const app = express();
const basicAuth = require('express-basic-auth');
const PORT = process.env.PORT || 5000;
app.use(basicAuth({
challenge: true,
users: { 'me': 'openforme' }
}))
.listen(PORT, () => console.log(`Listening on ${PORT}`));
I want that when the user and pass are correct app use:
app.use(express.static(path.join(__dirname, '/client/build')))
to see my web page

Change ip Nodejs

I created a mean stack application, I am deploying it in a virtual machine
the problem is that I need to change the localhost(localhost:4200) address to the ip of the machine 10.10.10.15(10.10.10.15:4200) I don't know how to do it
const path = require("path");
const express = require("express")
const mongoose = require("mongoose")
const db = require("./db/db")
const header_middleware = require("./middlewares/header")
const postRouter = require("./Routes/post");
const userRoutes = require("./Routes/user");
const profileRoutes = require("./Routes/profile");
var cors = require('cors');
const app = express()
app.use(cors({origin: '*'}));
const PORT = process.env.PORT || 3000
app.use(express.json())
app.use(header_middleware)
const directory = path.join(__dirname, './images');
app.use("/images", express.static(directory));
// app.use("/", express.static(path.join(__dirname, 'angular')));
app.use("/api/posts", postRouter)
app.use("/api/user", userRoutes);
app.use("/api/profile", profileRoutes);
app.get('/test', (req, res) => {
res.send('Hello World!')
})
app.listen(PORT, (req,res) => {
console.log(`app is listening to PORT ${PORT}`)
})
Instead of using your ip you can use your computer-name:4300 in your browser for example laptop-xxxxx:4300. To find your computer name you can go to about in your settings and it will say the name of your computer. If that doesn’t work check this answer out: https://stackoverflow.com/a/34659560/11365636

Express route returning 404 error

The express route in my node app is returning a 404 error. It works locally but on the production server it returns a 404 error (bear in mind that I changed the AJAX url to the one on my production server before uploading). My code:
server.js:
const path = require('path');
const http = require('http');
const express = require('express');
const publicPath = path.join(__dirname, '/../public');
const port = process.env.PORT || 8080;
var app = express();
var server = http.createServer(app);
app.use(express.static(publicPath));
app.post('/active-screens', function(req, res) {
res.send('route works!');
});
server.listen(port, () => {
console.log(`Server is up on port ${port}`);
});
index.js:
function checkRoute(){
$.ajax({
url: "http://localhost:8080/active-screens",
type: "POST"
})
.success(function(data){
console.log(data);
});
}
checkRoute();
It was a CORS issue as pointed out by #WejdDAGHFOUS.
I updated my server.js to this:
const path = require('path');
const http = require('http');
const express = require('express');
const cors = require('cors');
const publicPath = path.join(__dirname, '/../public');
const port = process.env.PORT || 8080;
var app = express();
var server = http.createServer(app);
app.use(express.static(publicPath));
app.post('/active-screens', cors(), function(req, res) {
res.send('route works!');
});
server.listen(port, () => {
console.log(`Server is up on port ${port}`);
});

Resources