How to add SSL on my NODE EXPRESS UBUNTU SERVER [closed] - node.js

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 16 hours ago.
Improve this question
Hi Please help to add ssl in node express app:
already add CERTBOT and create key.pem, cert.pem chain.pem.
this is my server.js file..
`require('express-async-errors')
require('dotenv').config()
const cors = require('cors')
const bodyParser = require('body-parser')
const morgan = require('morgan')
const mongoose = require('mongoose')
const producerRouter = require('./routes/producer')
const locationRouter = require('./routes/location')
const dataRouter = require('./routes/dataEntry')
const authRouter = require('./routes/auth')
const express = require('express')
const PORT = process.env.PORT || 3001
const api = process.env.API_URL
const app = express()
// Socket.io
const server = require('http').createServer(app)
const socketHandler = require('./controllers/socketHandler');
const io = socketHandler.socketHandler(server);
app.use(cors())
app.options('\*', cors())
app.use(express.json({limit: "20mb", extended: true}))
app.use(express.urlencoded({limit: "10mb", extended: true, parameterLimit: 50000}))
// middleware
app.use(bodyParser.json())
app.use(morgan('tiny'))
console.log(api)
console.log(`${api}/items`)
// authTokens
const publicUsersToken = require('./middleware/publicUsersAuthToken')
const producersToken = require('./middleware/producerAuthToken')
// Routes
// app.use(`${api}/producers`, producerRouter)
app.use(`/locations`, locationRouter)
app.use(`/cropTypes`, cropTypeRouter)
app.use(`/users`, userRouter)
app.use(`/items`, itemRouter)
app.use(`/marketItems`, marketItemRouter)
// app.use(`${api}/orders`, orderRouter)
app.use(`/dataEntries`, dataRouter)
app.use(`/districts`, districtRouter)
// CONNECTION_STRING
// MY_DB
mongoose.connect(process.env.CONNECTION_STRING, {
useNewUrlParser: true,
useUnifiedTopology: true,
dbName: 'agritech'
}
).then(() =\> {
console.log('Database Connection is ready')
}).catch((err) =\> {
console.log(err)
})
server.listen(PORT, () =\> {
console.log(`Server listening on http://localhost:${PORT}`)
})
convertOrdersSchedule();`
I want to install ssl on Express Backend APIs on ubuntu : MY_IP:3001 (https://123.12.1.1:3001)
Above I have given working server.js file, Please tell me what should I add in it so that the ssl will work.

Related

uri is returning undefined. Mongodb connection is not been established

enter image description here I need to know what's the problem. I am not getting the message on console for establishment of Mongodb database connection.
Here is a link to the error picture. https://drive.google.com/file/d/14cdAgAjfVX6R7pXND-FbjbK_3r-A3F-J/view?usp=share_link
server.js file
const express = require('express');
const cors = require('cors');
const mongoose = require('mongoose');
require('dotenv').config();
const app = express();
const port = process.env.port || 5000;
app.use(cors());
app.use(express.json());
// debugger
var uri; // Define outside
if(process.env.ATLAS_URI){
uri = process.env.ATLAS_URI; // Assign inside the block
}
mongoose.connect(uri, { useNewUrlParser: true, useCreateIndex: true}
);
const connection = mongoose.connection;
connection.once('open', () => {
console.log("MongoDB database connection established successfully");
})
const exercisesRouter = require('./routes/exercises');
const usersRouter = require('./routes/users');
app.use('/exercises', exercisesRouter);
app.use('/users', usersRouter);
app.listen(port, ()=> {
console.log(`Server is running on port: ${port}`);
});
.env file
ATLAS_URI = mongodb+srv://tripsy25:Mongo#123#cluster0.lwpkrde.mongodb.net/?retryWrites=true&w=majority
I tried to debug the code and found that uri was coming as undefined. Do I need to convert the password in ATLAS_URI to some other format?
The .env file must be located in the root folder of your project. And you should run the project from the root folder. Therefore:
Example 1
server.js
.env
Run it with node ./server.js
Example 2
src
|-server.js
.env
Run it with node ./src/server.js
You did one mistake in .env file
you did
ATLAS_URI = mongodb+srv://tripsy25:Mongo#123#cluster0.lwpkrde.mongodb.net/?retryWrites=true&w=majority
But you have to use url of atlas as an string
ATLAS_URI = "mongodb+srv://tripsy25:Mongo#123#cluster0.lwpkrde.mongodb.net/?retryWrites=true&w=majority"
The .env file must be located on the root folder and you must include it in the file where ever you need it at the very top.
and a few changings you just need to do and the things are good to go.
require('dotenv').config();
const express = require('express');
const cors = require('cors');
const mongoose = require('mongoose');
mongoose.set('useNewUrlParser', true);
mongoose.set('useFindAndModify', false);
mongoose.set('useCreateIndex', true);
mongoose.set('useUnifiedTopology', true);
const app = express();
const port = process.env.port || 5000;
app.use(cors());
app.use(express.json());
mongoose.connect(process.env.ATLAS_URI)
.then(() => {
console.log("DB connection successful")
app.listen(port, () => {
console.log(`app listening on port ${port}`);
})
})
.catch((err) => {
console.log(err)
})
const exercisesRouter = require('./routes/exercises');
const usersRouter = require('./routes/users');
app.use('/exercises', exercisesRouter);
app.use('/users', usersRouter);
I am not getting why you just create a var for ATLAS_URI. Just keep the code simple and neat and clean.

Express 4.17 req.body is empty

I'm hoping you can help me out here because after trying over a dozen s/o solutions and reading the express docs several times, I'm stumped. I'm building a Node app that will (in the end) accept a POST from the front end app, persist it to Mongo then allow back end users to manipulate the data. I am just getting going, trying to get the POST route working and have this so far:
app.js:
const express = require("express");
const cors = require("cors");
const mongoose = require('mongoose');
const AppData = require("./model/AppData");
const uri = "mongodb://localhost:27017/lunch"
mongoose.connect(uri, { useNewUrlParser: true, useCreateIndex: true, useUnifiedTopology: true });
const connection = mongoose.connection;
const router = require("./routes/index");
const PORT = 3005;
const app = express();
app.use(cors());
app.use("/", router);
app.use(express.raw({type: "application/json"}));
app.use(express.json({strict: false}));
connection.once('open', () => {
console.log('👍Successfully connected to MongoDB👍');
});
app.listen(PORT, function () {
console.log(`🚀The Backend Server is up and running on port ${PORT}🚀`);
});
index.js (routes...plan on changing the name)
const express = require('express');
const router = express.Router();
const appDataController = require('../controllers/appDataController');
router.post('/submit', appDataController.createAppData);
module.exports = router;
and appDataController.js:
const mongoose = require('mongoose');
const AppData = mongoose.model('AppData');
exports.createAppData = (req, res) => {
let reqData = req.body;
console.log(reqData);
res.send(reqData);
}
Simple enough, really, but when I grab Postman and set up a request using body/raw/json and send
{
"name": "John",
"age": "21"
}
I always see that body is undefined. From everything I've seen, I'm not doing anything wrong, but the result clearly indicates otherwise...What is it that I've missed?
Its because your using your express.json middleware after the routes, change this:
const express = require("express");
const cors = require("cors");
const mongoose = require('mongoose');
const AppData = require("./model/AppData");
const uri = "mongodb://localhost:27017/lunch"
mongoose.connect(uri, { useNewUrlParser: true, useCreateIndex: true, useUnifiedTopology: true });
const connection = mongoose.connection;
const router = require("./routes/index");
const PORT = 3005;
const app = express();
app.use(cors());
app.use(express.raw({type: "application/json"}));
app.use(express.json({strict: false}));
app.use("/", router); // this need to be here
connection.once('open', () => {
console.log('👍Successfully connected to MongoDB👍');
});
app.listen(PORT, function () {
console.log(`🚀The Backend Server is up and running on port ${PORT}🚀`);
});
first comes the middlewares and then the routes(depends on the middleware your using ofcurse).
You should also include urlencoded option to get the body on x-www-form-urlencoded body for POST requests.
const app = express();
app.use(cors());
app.use(express.raw({type: "application/json"}));
app.use(express.json({strict: false}));
app.use(express.urlencoded({extended: false})); // include this line
app.use("/", router);

Socket.io + node JS = Error during handshake: error code 500

I was working on Socket.io and node jS to develop a chat web app. It worked locally but I have faced many issues when I deployed my changes to Azure app service.
I am creating a secure connection on port 443. I have resolved other issues but I can't resolve this one.
This the error I'm getting in console on client side.
WebSocket connection to 'wss://mydomain/socket.io/?EIO=3&transport=websocket' failed: Error during WebSocket handshake: Unexpected response code: 500
This is how I'm connecting on server side
var socket = io.connect("https://mydomain:443", {transports: ['websocket'], secure: true, port: '443'});
and this is my server.js code:
const express = require("express");
const mongoose = require("mongoose");
const bodyParser = require("body-parser");
const passport = require("passport");
const users = require("./routes/api/users");
const base = require("./routes/api/base");
const leads = require("./routes/api/leads");
const requests = require("./routes/api/requests");
const offApp = require("./routes/api/offApp");
const chat = require("./routes/api/chat");
const chatSocket = require("./routes/socket/chat");
const path = require("path"); // on top
const app = express();
const cors = require('cors')
const https = require('https');
const fs = require('fs');
var options = {
pfx: fs.readFileSync('certificate.pfx'),
passphrase: 'password'
};
app.use(cors());
var server = https.createServer(options, app);
var client = require("socket.io").listen(server);
client.origins('*:*');
client.set('transports', ['websocket']);
server.listen(443);
// Bodyparser middleware
app.use(
bodyParser.urlencoded({
extended: false
})
);
app.use(bodyParser.json());
// DB Config
const db = require("./config/keys").mongoURI;
// Connect to MongoDB
mongoose
.connect(
db,
{ useNewUrlParser: true }, (err, db) => {
if (err) {
throw err;
}
console.log('MongoDB connected');
chatSocket(db, client);
});
// Passport middleware
app.use(passport.initialize());
// Passport config
require("./config/passport")(passport);
// Routes
app.use("/api/users", users);
app.use("/api/base", base);
app.use("/api/leads", leads);
app.use("/api/requests", requests);
app.use("/api/offapp", offApp);
app.use("/api/chat", chat);
const port = process.env.PORT || 5000;
app.use(express.static("client/build")); // change this if your dir structure is different
app.get("*", (req, res) => {
res.sendFile(path.resolve(__dirname, "client", "build", "index.html"));
});
app.listen(port, () => console.log(`Server up and running on port ${port} !`));
I have checked the logs, there are no errors there.

nodejs connection fail to database

i'm trying to build a simple rest api based on node.js + mongodb
i'm using https://cloud.mongodb.com/ and my connection string is 1000% correct
i keep having this problem sometimes it work for me all the day no issue
and sometimes it doesn't wanna connect and i changed nothing in the code
anyone is having similar issues?
const mongoose = require('mongoose');
const express = require('express');
const app = express();
const bodyParser = require('body-parser');
require('dotenv/config');
app.use(bodyParser.json());
// Import routes
const postsRoute = require('./routes/posts');
app.use('/posts', postsRoute);
//mongodb connect
mongoose.connect(process.env.db_access, { useNewUrlParser: true, useUnifiedTopology: true },
() => {
console.log('connected');
}
);
//ROUTES
app.get('/', (req,res) => {
res.send('home boi');
});
//listening port
app.listen(3000);

Cannot GET , nodejs

I tired to solve this problem, when I browse localhost:5000 I got error like
Cannot GET /
//*****************app.js************
const express = require('express');
const mongoose = require('mongoose');
const logger = require('morgan');
const bodyParser = require('body-parser');
const app = express();
const v1 = require('./routes/v1');
// ************* DB Config *************//
mongoose.connect(process.env.MONGO_DB_URL, {
useNewUrlParser: true,
useCreateIndex: true
});
mongoose.connection.on('connected' , () => {
console.log('Connected to the databse');
});
mongoose.connection.on('error' , (err) => {
console.error('Failed to connected to the databse: ${err}');
});
//**************Midlewares ***********//
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended : true}));
//*************Routes *****************//
app.use('/api/v1', v1);
module.exports = app ;
//********** index.js ***************//
require('dotenv').config();
const app = require('./src/app')
const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
console.log('Server is ready for connections on port ${PORT}');
});
the problem here is you have no route at the root /
you have to add either your routes you defined or define a root route

Resources