npm run build cannot find index.html in public subfolder - node.js

I continue to get the error below when I try to build a production version of my app. Npm run build is looking for my index.html file in public, but it thinks my public folder is in my root directory whereas it is in the client subfolder.
Could not find a required file.
Name: index.html
Searched in: C:\Users\wharfchillin\wharf-chillin-app\public
My public folder is located in a sub-folder of my app:
client
--->public
------>index.html
I have tried to make this clear in my server.js file in numerous ways:
UPDATED
const express = require("express");
const mongoose = require("mongoose");
const bodyParser = require("body-parser");
const passport = require("passport");
const path = require('path');
const users = require("./routes/api/users");
const plaid = require("./routes/api/plaid");
const app = express();
const publicPath = path.resolve(__dirname);
// Bodyparser middleware
app.use(
bodyParser.urlencoded({
extended: false
})
);
app.use(bodyParser.json());
app.use(express.static(publicPath));
app.use('*', (req, res) => {
res.sendFile(path.resolve(publicPath));
});
// production mode
if(process.env.NODE_ENV === 'production')
app.use(express.static(path.resolve(publicPath)));
console.log('test')
console.log(publicPath)
Any advice would be more than appreciated.

You are using window os, window os's path use backward slash, but in your node app, you are define the path using forward slash, node has api to handle this, path.resolve. Stop using path.join

Related

Serving Static file publically in nodejs :- Not Working

In my nodejs server file, I am trying to server static folder the code goes as below :-
server.js
const express = require("express");
const app = express();
require("dotenv").config();
const cookieParser = require("cookie-parser");
const bodyParser = require("body-parser");
const { connectDB } = require("./config/connectDB");
connectDB();
const upload = require("./routes/uploadsFile");
const user = require("./routes/user");
const path = require("path");
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(cookieParser());
app.use(express.json("content-type", "application/json"));
const publicFolder = path.join(__dirname, "../uploads");
console.log(publicFolder);
app.use(express.static(publicFolder));
app.use("/api/v1/upload", upload);
app.use("/api/v1/user", user);
const PORT = process.env.PORT || 3030;
app.listen(PORT, () => {
console.log(`Server Started Listening On PORT ${PORT}`);
});
The folder structures goes below :-
The same error I am getting as everyone
Cannot GET /uploads/image/actual-size/banner-Image-1.jpg
Can someone please help me. I have gone through many problem already answered like this on Stackoverflow, but unable to get the proper solution.
You defined uploads to be the root directory for serving static files which means the request paths must not start with /uploads. In your example above change the path to:
/image/actual-size/banner-Image-1.jpg
From the docs:
Express looks up the files relative to the static directory, so the
name of the static directory is not part of the URL.
I got the solution of the problem.
I was calling the GET URL by
localhost:${port}/uploads/image/actual-size/image.jpg
But I had to call like this because uploads folder is being server by default
localhost:${port}/image/actual-size/image.jpg

How to send css files with express js

I am having a hard time sending css files with express. The way my project is structured is I have a src folder and inside the src folder is the app.js for the express code as well as another folder titled "public". Inside of this public folder I have an experience.html page as well as an experience.css page. I can only get the html to render on the page and cannot get the css styling to show up. Attached is my code for the app.js page.
const express = require('express');
const app = express ();
const port = process.env.Port || 3000;
app.get('/experience', (req, res) => {
res.sendFile(__dirname+'/public/experience.html');
})
app.use(express.static('/public/experience.css'))
app.listen(port);
Just using middleware is enough, you don't need dedicated get routes to the files unless you want to mask some of the filenames.
This should work for your case
const express = require('express');
const path = require('path');
const app = express();
app.use(express.static(path.join(__dirname, 'public')));
app.listen(3000);
You can access them on http://localhost:3000/experience.html, http://localhost:3000/experience.css
You can use the Express static middleware with the path to the public folder.
Once you do that, you can expose a route to the files (or) you can access at localhost:9900
//Import modules
const express = require("express");
const path = require("path");
// Define PORT for HTTP Server
const PORT = 9900;
// Initialize Express
const app = express();
app.use(express.static(path.join(__dirname, "public")));
app.listen(PORT, (err) => {
console.log(`Your dog server is up and running!`);
});

How to deploy reactJS app with json-server

I have actually deployed my React-app in the following way:-
ran the command: npm run build
Already had db.json file with dummy data.
Context, when I run
json-server --watch db.json -p 3001 -d 2000
the entire react-app works on the localhost
installed json-server using npm
created a server.js file
const jsonServer = require('json-server');
const server = jsonServer.create();
const router = jsonServer.router('db.json');
const middlewares = jsonServer.defaults();
const port = process.env.PORT || 3001;
server.use(middlewares);
server.use(router);
server.listen(port);
created the app on heroku and pushed it to heroku master
The website for some reason only works when I run node server.js on my local-machine and it is making requests to my localport.
if that command isn't running the react-app cannot do the axios request to the DB.
I don't know what went wrong.
I used the following tutorial for this: https://github.com/jesperorb/json-server-heroku
My suspicions are that in my code I have created a basUrl.js file in which
export const baseUrl = 'http://localhost:3001/';
How should I change this to fix my problem?
Thanks for your help.
You should link your react folder built with the server (server.js), to do that add:
const express = require('express');
const path = require('path');
app.use(express.static(path.join(__dirname, 'build')));
app.get('/*', function (req, res) {
res.sendFile(path.join(__dirname, 'build', 'index.html'));
});
'build' is your react app's folder created after npm run build into your react app folder.
You have to install path and express modules if not.
And, You should get your json-server database in 'get' function, to use it with a specific url like: /db, just like this:
app.use('/db', middlewares, router);
But you should put /db before /* to not to open database with url /.
So, the result (server.js) will be:
const jsonServer = require('json-server');
const app = jsonServer.create();
const path = require('path');
const express = require('express');
const middlewares = jsonServer.defaults();
const router = jsonServer.router('db.json');
const port = process.env.PORT || 3001;
app.use('/db', middlewares, router);
app.use(express.static(path.join(__dirname, 'build')));
app.get('/*', function (req, res) {
res.sendFile(path.join(__dirname, 'build', 'index.html'));
});
server.listen(port);
I have Heroku running on my JSON server too. You need to correct your API path to be your resource name, for example;
If your resource name in your API is 'blogs';
{
"blogs": [
{
"postTitle": "My First Blog",
then your api path will be;
https://xxxx.herokuapp.com/blogs
OR
export const baseUrl = 'https://xxxx.herokuapp.com/blogs';
You shouldn't need to specify a port, but if you do it will be port 4000, which Heroku uses.

How launch an express Web Node.js from a batch file

I have an app.js script that contains an express node website
const express = require('express');
const app = express();
const path = require('path');
const router = express.Router();
const fs = require('fs');
var bodyParser = require('body-parser');
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
extended: true
}));
app.use(express.static('public'));
…
app.listen(3000, function () {
console.log('avalaible at http://localhost:3000');
});
until now I launch website by writing in cmd
node ./app.js
Then I go to adress http://localhost:3000 in my browser
I would have a batch or another way to those operations just by doucle click on a file
Could you help me please?
In the Node js project folder create a .bat file and put this on it:
node ./app.js
start "" http://localhost:3000
when you click the file this should launch your nodejs app and open your default browser on the given address.

No content in <app-root> element in browser using the command "node app.js"

I created an Angular 7 application using the Angular CLI. I added my express server as one knows it. Afterwards I used the command "node server/app.js to start my app, but then in the browser in the "Elements" section there appears <app-root></app-root> without any content. As if the browser knew nothing about the actual Angular application. And when I run the ng serve command it seems to know about the actual Angular application, but there appears a 404 not found error in terms of post and get requests to the data server.
I already had a working Angular4 application with -I guess- the same setup and now same things seem to not work any longer.
I researched all day long to find the solution but for nothing.
I think it is not advantageous to post all my files in here. Comment if I was wrong and I am going to edit them.
Thanks in advance.
My app.js:
"use strict";
var bodyParser = require('body-parser');
const cors = require('cors');
// import { Observable } from 'rxjs';
var express = require("express");
var path = require("path");
var app = express();
app.use(cors());
const router = express.Router();
var nodeModulesPath = path.join(__dirname, "..", "node_modules");
app.use("/node_modules", express.static(nodeModulesPath));
var srcPath = path.join(__dirname, "..", "src");
app.use("/src", express.static(srcPath));
var serverPath = path.join(__dirname);
app.use("/server", express.static(serverPath));
// app.use(bodyParser.json());
var models = require("./models");
models.sequelize.sync({force:true}).then(function() {
console.log("TABELLE ERSTELLT");
// app.use(cors());
app.use("/", router);
app.use(bodyParser
.urlencoded({extended:true})
);
app.use(bodyParser.json());
console.log("after bodyparser");
app.get("/", function(req,res){
res.sendFile(path.join(__dirname, "views", "index.html"));
});
// app.get('/*', function(req, res) {
// res.sendFile(path.join(__dirname, "views", "index.html"));
// });
app.post("/goals/create",function (req, res){
models.Goal.create({
id: req.body.id,
name: req.body.name,
content: req.body.content,
firstGivenValue: req.body.firstGivenValue,
fittingValue: req.body.fittingValue,
someone_would_like_to_implement: req.body.someone_would_like_to_implement,
i_know_how_to_implement_it: req.body.i_know_how_to_implement_it
}).then(function(obj){
console.log(obj.id);
// res.end("erfolgreich");
res.redirect("/");
})
console.log(req.body);
});
app.get("/test",(req, res) => {
res.end("test erfolgreich");
});
app.listen(3000);
});
You mention that you think it used to work for angular 4. Currently you're serving the index.html from the src folder. That's not going to work, your app is a typescript app and will need to be compiled one way or another; not to mention the Angular compiler. In the early days (I think pre 4, but not sure) angular serve also write the served files in a folder in your project, so you could just pick those JIT compiled files up and toss them on a web server, or express server. Those days are gone (with good reason for that matter, mostly performance).
You will now have to create an explicit build (ng build) and tell your express server (app.js) to target your dist folder.
TL;DR:
Run ng build
Replace
var srcPath = path.join(__dirname, "..", "src");
app.use("/src", express.static(srcPath));
With:
var distPath = path.join(__dirname, "..", "dist");
app.use("/dist", express.static(distPath));

Resources