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.
Related
The app works fine on GET requests. But on a POST request with body an application error occurs. I can't figure out this problem.
My app setup using express is like this:
const express = require('express');
const cors = require('cors');
const jwt = require('jsonwebtoken');
const { MongoClient, ServerApiVersion, ObjectId } = require('mongodb');
require('dotenv').config()
const port = process.env.PORT || 5000
const app = express()
app.use(cors())
app.use(express.json())
app.get('/', (req, res) => {
res.send('Express Server Running...✔')
})
app.listen(port, () => {
console.log('Listening to port', port);
})
I wrote this code in my node app
const express = require("express");
const cors = require("cors");
const pool = require("./db");
const app = express();
//middleware
app.use(cors);
//access req.body
app.use(express.json());
app.get("/", async (req, res) => {
try {
res.json("response from server");
// const allCompanies = await pool.query("SELECT * FROM COMPANIES");
// res.json(allCompanies.rows);
} catch (error) {
console.log(error.message);
}
});
const port = 1337;
app.listen(port, () => {
console.log(`Server is starting on port ${port}`);
});
In my terminal it says its running on 1337 however when i try to connect to postman it leaves me hanging? never had this problem before.
const express = require("express");
const cors = require("cors");
const app = express();
app.use(cors());
The problem was that you were not calling the cors function on your app.use middleware.
If you change the code to
app.use(cors());
It should work.
Express Documentation
I'm having some issues with my application after it's been deployed to heroku. When I specify the URL, or refresh the browser on a page OTHER than the homepage I am getting an "Internal Server error" and the page doesn't load. However when I click the links which naviagte me to those pages from the home page it works fine. When I run the server locally it does not give me this error.
Based on my research this is probably an error on the server side. Here is my code:
Node.js backend
const express = require("express");
const bodyParser = require("body-parser");
const passport = require("passport");
const users = require("./routes/api/users");
const actions = require("./routes/api/dbActions");
const app = express();
// Bodyparser middleware
app.use(
bodyParser.urlencoded({
extended: false
})
);
app.use(bodyParser.json());
// Passport middleware
app.use(passport.initialize());
// Passport config
require("./config/passport")(passport);
// Routes
app.use("/api/users", users);
app.use("/api/dbActions", actions);
// Serve static assets if in production
if (process.env.NODE_ENV === 'production') {
// Set static folder
app.use(express.static('client/build'));
app.get('*', (req, res) => {
res.sendFile(path.resolve(__dirname, 'client', 'build', 'index.html'));
});
}
const port = process.env.PORT || 5000;
app.listen(port, () => console.log(`Server running on port ${port} !`));
Any idea why this might be happening?
Thanks!!
In my server.js file I included the following:
const path = require('path');
Which seems to have worked for me.
I want to deploy my app to aws, i search and i found alot of tutorials i try each one and i get this error on the browser:
Cannot GET /
I figure maybe that my problem is from my nodeJS server code.
This is my server.js code hope you guys can help me thanks.
const express = require('express');
const mongoose = require('mongoose');
const bodyParser = require('body-parser');
const passport = require('passport');
const path = require('path');
const cors = require('cors');
//Api routes
const users = require('./routes/api/usuario');
const alumno = require('./routes/api/alumno');
const personal = require('./routes/api/personal');
const zonas = require('./routes/api/zonas');
const sepomex = require('./routes/api/sepomex');
const app = express();
app.use(cors());
//Body parser middleware
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
//Db config
const db = process.env.NODE_ENV === "production" ? require('./config/keys').mongoURIProd : require('./config/keys').mongoURIDev;
//connect to mongo DB
mongoose
.connect(db, { useNewUrlParser: true })
.then(() => console.log('MongoDB Connected'))
.catch(err => console.log(err));
//passport middleware
app.use(passport.initialize());
//passport config
require('./config/passport')(passport);
//Use routes
app.use('/api/usuario', users);
app.use('/api/alumno', alumno);
app.use('/api/personal', personal);
app.use('/api/zonas', zonas);
app.use('/api/sepomex', sepomex);
//serve static assets to production
if (process.env.NODE_ENV === "production") {
//static folder
app.use(express.static("client/build"));
app.get('/*', (req, res) => {
res.sendFile(path.resolve(__dirname, 'client', 'build', 'index.html'));
})
}
const port = process.env.PORT || 5000;
app.listen(port, () => {
console.log(`Server running on port ${port}`);
});
I have deployed my app on heroku and works fine.
If you are deploying to EC2 instance then you need to specify IP address in app.listen to be 0.0.0.0, by default it is set to localhost which is not what you want if you want the app to be reachable from outside.
You should change your code to
app.listen(port, '0.0.0.0', () => {
console.log(`Server running on port ${port}`);
});
I have an Angular 7 project with PWA functionality added.
I basically have all PWA-related settings set to default.
My issue is, that offline mode does not work when deploying the project to my server. It's also not working when starting the server on localhost.
However, when using the npm module http-server to host the app on localhost, the offline mode works.
Online the service worker is applied:
Here is what happens when loading app offline:
The code of my Node.Js server looks like this:
require('module-alias/register')
const express = require('express')
const app = express()
const prod = require('#root/prod')
const port = process.env.PORT || 3000
const path = require('path')
const compression = require('compression')
app.use(compression())
const bodyParser = require('body-parser')
app.use(bodyParser.json())
app.use(bodyParser.urlencoded({ extended: true }))
app.use(express.static(path.join(__dirname, '../client/dist/client')));
const api = require('#root/api/api.routes')
app.use('/api', api)
app.get('*', (req, res) => {
res.status(200).sendFile(path.join(__dirname, '../client/dist/client/index.html'))
})
app.use(function (err, req, res, next) {
console.log('error occured', err.stack);
res.status(500).send({ "Error": err.stack });
});
app.listen(port, () => {
console.log(`• • •`)
console.log(`• Server launched 🚀 on port`, port)
console.log(`• Server running in ${prod ? '🔥 production' : '💉 development'} mode`)
console.log(`• • •`)
})
Here are all files from the production build: