https://peaceful-basin-17224.herokuapp.com/
Of course, "it works on my machine".
When I look at the network, I see the assets being loaded from index.html but nothing else.
Also, for some reason the npm run build doesn't seem to run. I'll heroku bash into the app and I won't find a /frontend/build
I've been messing with this since last night and feel like I haven't made any progress. Any help would be appreciated!
Part of my server.js
app.use(express.static(path.join(__dirname, '/frontend')));
app.get('/*', function (req, res) {
res.sendFile(path.join(__dirname, '/frontend/public', 'index.html'));
});
app.use(express.static(__dirname +'frontend'));
//Serve static assests if in production
if(process.env.NODE_ENV === 'production'){
//Set static folder
app.use(express.static('frontend/build'));
app.get('*', (req, res)=>{
res.sendFile(path.resolve(__dirname, 'frontend', 'public', 'index.html')) });
}
Here's my package.json:
{
"name": "backend",
"version": "1.0.0",
"description": "",
"proxy": "http://localhost:3001",
"main": "server.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"start": "node server.js",
"server": "nodemon server.js",
"heroku-postbuild": "NPM_CONFIG_PRODUCTION=false npm install --prefix frontend && npm run build"
},
"author": "",
"license": "ISC",
"dependencies": {
"#mailchimp/mailchimp_marketing": "^3.0.69",
"express": "^4.17.1",
"simple-react-modal": "^0.5.1"
}
}
I think you can delete all of this code:
app.use(express.static(path.join(__dirname, '/frontend')));
app.get('/*', function (req, res) {
res.sendFile(path.join(__dirname, '/frontend/public', 'index.html'));
});
app.use(express.static(__dirname +'frontend'));
//Serve static assests if in production
if(process.env.NODE_ENV === 'production'){
//Set static folder
app.use(express.static('frontend/build'));
app.get('*', (req, res)=>{
res.sendFile(path.resolve(__dirname, 'frontend', 'public', 'index.html')) });
}
and put only this:
app.use(express.static(path.join(__dirname, './frontend/build')));
My react.js folder had the name "frontend" and it was at the same level with my server.js file, that's why it is one dot ./frontend/build. And don't remove build name and dont change it to any other name.
And please let me know if this answer helps.
Related
Trying to make my first Vue application, simple game with MEVN stack. Working perfect interacting with backend on development environment, however when hosting it doesn't fetch the data from the server.
Anyone able to point out what I have incorrect with the below?
More info below:
File structure:
/root
|- config.js
|- server.js
|- package.json + package-lock.json
|- client/
|- vue.config.json
|- ... (rest of dist, src, node_modules, public etc.)
|- models/
|- Elf.js + HighScore.js
|- routes/
|- api/
|- elf.js + highScore.js
config.js
module.exports = {
hostUrl: process.env.HOST_URL,
mongoURI: process.env.MONGO_URI,
PORT: process.env.PORT || 3000,
};
server.js
const express = require("express");
const app = express();
const port = 3000;
const mongoose = require("mongoose");
const { PORT, mongoURI } = require("./config.js");
// routes
const Player = require("./routes/api/player");
const Elf = require("./routes/api/elf");
const HighScore = require("./routes/api/highScore");
// cors is a middleware that allows us to make requests from our frontend to our backend
const cors = require("cors");
// morgan is a middleware that logs all requests to the console
const morgan = require("morgan");
// body-parser is a middleware that allows us to access the body of a request
const bodyParser = require("body-parser");
const path = require("path");
app.use(cors());
// use tiny to log only the request method and the status code
app.use(morgan("tiny"));
app.use(bodyParser.json());
// chek if we are in production
if (process.env.NODE_ENV === "production") {
// check if we are in production mode
app.use(express.static("client/dist"));
app.get("*", (req, res) => {
res.sendFile(path.resolve(__dirname, "client", "dist", "index.html"));
});
}
// test if server is running and connected to mongoDB
app.get("/", (req, res) => {
res.send("Hello World!");
});
// app.get("/", (req, res) => {
// res.send("Hello World!");
// });
// use routes
app.use("/api/", Player);
app.use("/api/", Elf);
app.use("/api/", HighScore);
mongoose
.connect(mongoURI, {
useNewUrlParser: true,
useUnifiedTopology: true,
useUnifiedTopology: true,
})
.then(() => console.log("MongoDB connected..."))
.then(() => {
// log uri to console
console.log(`MongoDB connected to ${mongoURI}`);
})
.catch((err) => console.log(err));
app.listen(PORT, () => {
console.log(`Example app listening at ${PORT}`);
});
package.json
{
"name": "week1",
"version": "1.0.0",
"description": "",
"main": "server.js",
"scripts": {
"server": "nodemon server.js --ignore 'client/'",
"client": "npm run serve --prefix client",
"dev": "concurrently \"npm run server\" \"npm run client\"",
"start": "node server.js",
"build": "npm install --prefix client && npm run build --prefix client"
},
"keywords": [],
"author": "",
"license": "ISC",
"dependencies": {
"body-parser": "^1.20.1",
"bootstrap": "^5.2.3",
"cors": "^2.8.5",
"dotenv": "^16.0.3",
"express": "^4.18.2",
"mongoose": "^6.7.5",
"morgan": "^1.10.0",
"portal-vue": "^2.1.7"
},
"devDependencies": {
"concurrently": "^7.6.0",
"nodemon": "^2.0.20"
}
}
Running within my dev environment at root dir using 'npm run dev', the app works flawlessly send/ receive data from mongoDB during this time. This starts up http://localhost:8080/. Also tried install of 'npm install -g serve' and running 'serve -s dist', this starts up serving at localhost:36797 and working flawlessly too.
I have tried to setup on Vercel & Render, both giving me the same issue where I'm not getting much feedback and the data isn't being fetched. Anyone else has this issue before?
I am hosting my very simple nodejs server in Heroku. But, when I try it, it returns this error:
Application error
An error occurred in the application and your page could not be served. If you are the application
owner, check your logs for details. You can do this from the Heroku CLI with the command`
Here's the server.js:
const express = require("express");
const cors = require("cors");
const PORT = process.env.PORT || 80;
const server = express();
server.use(cors());
server.get("/", (req, res) => {
const INDEX = "/index.html";
res.sendFile(INDEX, { root: __dirname });
});
server.get("/test", (req, res) => {
res.send("test Page");
});
server.listen(PORT, () => console.log(`listening on port ${PORT}`));
package.json:
{
"name": "express-heroku",
"version": "1.0.0",
"description": "",
"main": "server.js",
"engines": {
"node": "15.11.x"
},
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"start": "node server.js"
},
"author": "",
"license": "ISC",
"dependencies": {
"express": "^4.17.1",
"mongoose": "^5.11.19"
},
"devDependencies": {
"nodemon": "^2.0.7"
}
}
Don't know what the reason is, but, when I try this in the localhost it works perfectly!
The full error on Heroku CLI:
Any help is greatly appreciated !
Create a ProcFile:
Inside the ProcFile add web: node index.js
Doing this, you are telling heroku to run your server, with node.
Hi Guys, I have created a little project of Mern stack. I am deploying it correctly on Heroku. But as soon as I am checking her on Heroku after deploying, then Failed to load resource: the server responded with a status of 503 (Service Unavailable) error is coming.
But as soon as I run heroku local in cmd after deploying then it is working correctly. I am giving below the heroku setup code. Please guide me. please ........
package.sjon file of backend
{
"name": "app",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"start": "npm install && node index",
"heroku-postbuild": "NPM_CONFIG_PRODUCTION=false npm install --prefix client && npm run build --prefix client"
},
"dependencies": {
"config": "^3.3.1",
"express": "~4.16.1",
"express-fileupload": "^1.1.7-alpha.3",
"mongoose": "^5.9.12",
"nodemailer": "^6.4.6"
},
"keywords": [],
"author": "",
"license": "ISC"
}
Index.js file of backend
var express = require('express');
var path = require('path');
const connectDB = require('./config/db')
var indexRouter = require('./routes/index');
var usersRouter = require('./routes/users');
var studentRouter = require('./routes/student')
var app = express();
connectDB();
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(express.static(path.join(__dirname, 'public')));
app.use(express.static('client/build'))
app.get('/', (req, res) => {
res.sendFile(path.resolve(__dirname, 'client', 'build', 'index.html'))
})
app.use('/', indexRouter);
app.use('/', studentRouter);
app.use('/users', usersRouter);
if (process.env.NODE_ENV == "production") {
app.use(express.static('client/build'))
app.get('*', (req, res) => {
res.sendFile(path.resolve(__dirname, 'client', 'build', 'index.html'))
})
}
var port = process.env.PORT || '8000';
app.listen(port, () => {
console.log(`server run port ${port}`);
})
module.exports = app;
All these codes are absolutely correct. I had a problem creating a cluster in mongodb atlas. The problem was that I had selected add current ip address while creating the cluster. Whereas I had to select allow from anywhere. So now I have selected the book. And now it is doing the right thing.
In my case, changing network access form anywhere in my MongoDB cluster, fixed the problem.
Also, don't forget to hit restart all dynos.
I am new to Nodejs and I am following a course on Pluralsight for Nodejs using express.
I have the following code:
var express = require('express');
var app = express();
var port = 5000;
app.use(express.static('public'));
app.get('/', function (req, res) {
res.send('Hello World');
});
app.get('/books', function (req, res) {
res.send('Hello Books');
});
app.listen(port, function (err) {
console.log('running server on port ' + port);
});
And then from the command line I run the following:
$ npm start
This is my json file:
{
"name": "library",
"version": "1.0.0",
"description": "",
"main": "app.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"start": "node app.js"
},
"author": "",
"license": "ISC",
"dependencies": {
"express": "^4.14.0"
}
}
Now the problem I am having is that when from my browser I put: localhost:5000 everything looks fine. I see my Hello World text. But when I am trying to go to a folder under the public such as localhost:5000/css/style.css I get the following error message.
Cannot GET /css/style.css
And here is my folder structure
If you want:
localhost:5000/css/style.css
to be served by:
app.use(express.static('public'));
Then, you need to make sure that style.css is in:
public/css/style.css
where public/css/style.css is evaluated relative to the current working directory.
You don't disclose your file hierarchy, but if localhost:5000/css/style.css isn't working, then apparently style.css isn't located properly in public/css/style.css or your public directory isn't in the proper place.
app.use(express.static('public')); tells express to look for requested files relative to the public directory. So a request for /css/style.css will be looked for at public/css/style.css.
Also, app.use(express.static('public')); assumes that the public directory you want it to look in is relative to the working directory when the app.use() statement is run so you need to either make sure that is also correct or you need to put an absolute path in the express.static() statement so you don't depend on the current working directory.
I'm very new to Node. I just installed it via Brew and when I ran node server.js in the Terminal, the Terminal does nothing for hours.
node -v
v6.6.0
This is the server file, it is from a tutorial video that I'm watching. The point of this simple express server is to allow me the ability to quickly serve test data via HTTP to the front-end.
package.json :
{
"name": "simple-server",
"version": "1.0.0",
"description": "",
"main": "server.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"start": "node server.js"
},
"author": "",
"license": "ISC",
"dependencies": {
"body-parser": "^1.14.1",
"express": "^4.13.3",
"path": "^0.12.7"
}
}
server.js file :
var express = require('express');
var path = require('path');
var bodyParser = require('body-parser');
var app = express();
//Allow all requests from all domains & localhost
app.all('/*', function(req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "X-Requested-With, Content-Type, Accept");
res.header("Access-Control-Allow-Methods", "POST, GET");
next();
});
app.use(express.static(path.join(__dirname + '/public')));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: false}));
var persons = [
"person1.jpg",
"person2.jpg",
"person3.jpg",
"person4.jpg",
"person5.jpg",
"person6.png"
];
app.get('/persons', function(req, res) {
console.log("GET From SERVER");
res.send(persons);
});
app.listen(6069);
Thanks in advance
Try adding a console.log("started!") before app.listen. I'm guessing the server starts, but as is seen in your code, the only log it does is when it receives a request.
Try accessing http://localhost:6069/persons in your browser.
Edit: this defines a server response
app.get('/persons', function(req, res) {
console.log("GET From SERVER");
res.send(persons); <-- server sends persons array to client
});