Unable to connect mongoDb to Express - javascript

I am making a registration form with the MERN stack, I am connecting Express app to mongoDB but I am getting error in connection.
I am following Thapa Technical video on YouTube, and I have done exactly what Thapa did, I don't know what is wrong in this, I am a beginner please help me.
app.js file:
const express = require('express');
const app = express();
require("./db/conn")
const port = process.env.PORT || 3000;
app.get("/", (req, res) => {
res.send("Welcome to Abdullah's webbsite")
});
app.listen(port, () => {
console.log(`Server is running at port no ${port}`)
})
conn.js file:
const mongoose = require("mongoose");
mongoose.connect("mongodb://localhost:27017/userRegistration", {
useNewUrlParser:true,
useUnifiedTopology:true,
useCreateIndex:true
}).then(() =>{
console.log(`Connection Successful`);
}).catch((e) => {
console.log(e);
})
package.json file:
{
"name": "registration-form",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"dev" : "nodemon src/app.js"
},
"author": "Abdullah",
"license": "ISC",
"dependencies": {
"express": "^4.17.3",
"hbs": "^4.2.0",
"mongoose": "^6.2.2"
}
}
console:
Server is running at port no 3000
MongoParseError: option usecreateindex is not supported
at parseOptions (C:\Users\ABDULLAH\Desktop\Registration Form\Registration form\node_modules\mongodb\lib\connection_string.js:289:15)
at new MongoClient (C:\Users\ABDULLAH\Desktop\Registration Form\Registration form\node_modules\mongodb\lib\mongo_client.js:62:63)
at C:\Users\ABDULLAH\Desktop\Registration Form\Registration form\node_modules\mongoose\lib\connection.js:784:16
at new Promise (<anonymous>)
at NativeConnection.Connection.openUri (C:\Users\ABDULLAH\Desktop\Registration Form\Registration form\node_modules\mongoose\lib\connection.js:781:19)
at C:\Users\ABDULLAH\Desktop\Registration Form\Registration form\node_modules\mongoose\lib\index.js:340:10
at C:\Users\ABDULLAH\Desktop\Registration Form\Registration form\node_modules\mongoose\lib\helpers\promiseOrCallback.js:32:5 at new Promise (<anonymous>)
at promiseOrCallback (C:\Users\ABDULLAH\Desktop\Registration Form\Registration form\node_modules\mongoose\lib\helpers\promiseOrCallback.js:31:10)
at Mongoose._promiseOrCallback (C:\Users\ABDULLAH\Desktop\Registration Form\Registration form\node_modules\mongoose\lib\index.js:1140:10)

Please remove useCreateIndex option in connn.js:
mongoose.connect("mongodb://localhost:27017/userRegistration", {
useNewUrlParser:true,
useUnifiedTopology:true
}).then(() =>{
console.log(`Connection Successful`);
}).catch((e) => {
console.log(e);
})

const express = require('express');
const mongoose = require('mongoose');
const app = express();
app.use(express.json());
let userModel;
// configure mongoose
mongoose.connect('mongodb://localhost:27017/userRegistration', (err) => {
if (err) {
console.log(`Error connecting to mongodb => `, err);
} else {
console.log(`Mongodb Connected successfully`);
}
});

Related

socket.io 'on' doesn't get fired with Nodejs server

server.js
const express_l = require('express');
const path_l = require('path');
const app_l = express_l();
const http_l = require('http');
const server_l = http_l.createServer( app_l);
const socketio_l = require('socket.io');
const io_l = socketio_l( server_l);
app_l.use( express_l.static( path_l.join( __dirname, 'public')) );
io_l.on( "connection", argSocket => { console.log('New websocket connection!'); });
var PORT = 3000 || process.env.PORT;
server_l.listen( PORT, ()=>{ console.log(`from express server on port ${PORT}!`) });
main.js
const socket = io_l();
chat.html
...
...
<script src = "/socket.io/socket.io.js"> </script>
<script src = "js/main.js"> </script>
</body>
</html>
package.json
{
"name": "chatcord",
"version": "1.0.0",
"description": "Realtime chat application built with Nodejs",
"main": "server.js",
"scripts": {
"start": "node server",
"dev": "nodemon server"
},
"author": "xyz",
"license": "MIT",
"dependencies": {
"express": "^4.18.1",
"moment": "^2.29.3",
"socket.io": "^4.5.1"
},
"devDependencies": {
"nodemon": "^2.0.16"
}
}
Now, when I refresh http://localhost:3000/ in browser, I don't see the console.log statement from the on function of socket.io.
Where am I going wrong? Please point out.
Your initialization is wrong. You have to create a new instance of the socket io server and then call it. Check the documentation for more.
https://socket.io/get-started/chat#integrating-socketio
const { Server } = require("socket.io");
const io = new Server(server);
io.on('connection', (socket) => {
console.log('a user connected');
});
Hopefully this helps.
this is from socket io documentation
https://socket.io/get-started/chat
const express = require('express');
const app = express();
const http = require('http');
const server = http.createServer(app);
const { Server } = require("socket.io");
const io = new Server(server);
io.on("connection", async (socket) => {
console.log("someone connected to socket")
//add listener here
socket.on("chat",(data)=> {
console.log(data)
})
});
httpServer.listen(port, host, () => {
console.log(`Server running on http://${host}:${port}`);
});
also this is the emit cheatsheet maybe useful for you
https://socket.io/docs/v3/emit-cheatsheet/
You're consoling on nodejs server so check your terminal for the output of the console.
You need to research how emitting events works in socket (helping material)

Express router working fine locally but not on heroku

My express app works fine on the localhost but it does not work on Heroku.
When I added a line it stops working and
the line is
app.use("/api/product", require("./routes/product"))
Here is the code
Index.js
const express = require("express");
const app = express();
const port = process.env.PORT || 5000;
app.get("/", (req, res) => {
res.send("responded")
});
app.use(express.json())
app.use("/api/product", require("./routes/product"))
app.listen(port, () => {
console.log(`Example app listening at http://localhost:${port}`);
});
product.js
const express = require("express");
const router = express.Router();
router.get("/", async (req, res) => {
try {
res.json({
status: 200,
message: "Data has been successfully fetched"
});
}
catch (error) {
console.log(error);
return res.status(400).send("server error")
}
})
module.exports = router;
package.json
{
"name": "backend-test",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"start": "node index.js",
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "",
"license": "ISC",
"dependencies": {
"express": "^4.17.3"
}
}
Folder structure
You would wanna switch your route handlers place. Otherwise you will never rich your api, as the first catches all requests.
const express = require("express");
const app = express();
const port = process.env.PORT || 5000;
app.use(express.json())
app.use("/api/product", require("./routes/product"))
app.get("/", (req, res) => {
res.send("responded")
});
app.listen(port, () => {
console.log(`Example app listening at http://localhost:${port}`);
});

str.CharAt is not a function - when trying to access server route

I'm not sure what I did, but I broke something. Trying to deploy an API to Heroku. Everything was fine locally but then I guess I did something wrong and now it's all broken. It works when I go just localhost:5000 and displays that page (which just says "hello world") but when I try to access anything with the API parameters eg: localhost:5000/data/2018-10/gen6ou it just sits. No error is shown in the console. In the terminal, where i ran the command: node index.js it displays: str.charAt is not a function but does not break the connection or anything.
index.js
const express = require('express');
const app = express();
const pool = require("./db"); //stores super secret db info
const cors = require("cors");
const PORT = process.env.PORT || 5500;
// middleware
app.use(cors());
app.use(express.json()); // => req.body
app.use(express.static('public')); //index.html, just says 'hello world'
// get the data
app.get("/data/:date/:tier", async (req, res) => {
try {
const { date, tier } = req.params;
const allData = await pool.query(
"SELECT * FROM smogon_usage_stats WHERE date=$1 AND tier=$2",
[date, tier]
);
const results = allData.rows;
const output = { "data": Object.fromEntries(
results.map(
item => [item.pokemon, item]
))
};
res.json(output);
} catch (error) {
console.log(error.message);
};
});
app.listen(PORT, () => {
console.log(`Server running on port ${PORT}.`);
});
package.json
{
"name": "usage_server",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"start": "node index.js"
},
"keywords": [],
"author": "",
"license": "ISC",
"dependencies": {
"cors": "^2.8.5",
"dotenv": "^8.2.0",
"express": "^4.17.1",
"pg": "^8.5.1"
},
"engines": {
"node": "14.16.0",
"npm": "6.14.11"
},
"proxy": "http://localhost:5000"
}
db.js
const { Pool } = require('pg');
require("dotenv").config();
const devConfig = `postgresql://${process.env.PG_USER}:
${process.env.PG_PASSWORD}#${process.env.PG_HOST}:
${process.env.PG_PORT}/${process.env.PG_DATABASE}`;
const proConfig = {
connectionString: process.env.DATABASE_URL
};
const conn = new Pool({
connectionString: process.env.NODE_ENV === "production" ? devConfig : proConfig
});
module.exports = conn;
In production, your database config object is invalid - the connectionString contains another object (the proConfig).
You seem to be looking for either
const devConfig = {
connectionString: `postgresql://${process.env.PG_USER}:${process.env.PG_PASSWORD}#${process.env.PG_HOST}:${process.env.PG_PORT}/${process.env.PG_DATABASE}`
};
const proConfig = {
connectionString: process.env.DATABASE_URL
};
const conn = new Pool(process.env.NODE_ENV === "production" ? devConfig : proConfig);
or
const connectionString = process.env.NODE_ENV === "production"
? process.env.DATABASE_URL
: `postgresql://${process.env.PG_USER}:${process.env.PG_PASSWORD}#${process.env.PG_HOST}:${process.env.PG_PORT}/${process.env.PG_DATABASE}`;
const conn = new Pool({ connectionString });

Deploying app to Heroku throws error { path=β€œ/” path=β€œ/favicon.ico” }. But runs on localhost

I am trying to deploy my app to Heroku. I am getting 503 (Service Unavailable) error even though it runs on localhost. I have tried many solutions, but none of them are working. My app.js file
if (process.env.NODE_ENV !== "production") {
require("dotenv").config();
}
const express = require("express");
const mongoose = require("mongoose");
const { ApolloServer } = require("apollo-server-express");
const auth = require("./middleware/auth");
const userController = require("./controllers/userController");
const typeDefs = require("./schema");
const resolvers = require("./resolvers");
const port = process.env.PORT || 4000;
const app = express();
app.set("port", port);
app.use((req, res, next) => {
res.setHeader("Access-Control-Allow-Origin", "*");
res.setHeader(
"Access-Control-Allow-Methods",
"OPTIONS, GET, POST, PUT, PATCH, DELETE"
);
res.setHeader("Access-Control-Allow-Headers", "Content-Type, Authorization");
next();
});
app.use(auth);
app.get("/email-confirmation/:token", userController.confirmationPost);
const server = new ApolloServer({
typeDefs,
resolvers,
formatError: (err) => {
if (!err.originalError) {
return err;
}
if (err.message.startsWith("Database Error: ")) {
err.message = "Internal server error";
}
const data = err.originalError.data;
const message = err.message || "Internal server error.";
const code = err.originalError.code || 500;
return { message: message, status: code, data: data };
},
context: ({ req, res }) => ({
req,
res,
}),
});
server.applyMiddleware({ app });
mongoose
.connect(process.env.DB_URL, {
useNewUrlParser: true,
useUnifiedTopology: true,
useCreateIndex: true,
})
.then(() => {
console.log("conneted to database");
app.listen(port, () => {
console.log("listening for requests on port " + port);
});
});
And my package.json is:
{
"name": "server",
"version": "1.0.0",
"description": "",
"main": "app.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"start": "node app.js",
"dev": "nodemon app.js"
},
"author": "",
"license": "ISC",
"dependencies": {
"apollo-server-express": "^2.17.0",
"bcryptjs": "^2.4.3",
"crypto": "^1.0.1",
"express": "^4.17.1",
"graphql": "^15.3.0",
"jsonwebtoken": "^8.3.0",
"mongoose": "^5.10.2",
"nodemailer": "^6.4.16",
"nodemailer-sendgrid-transport": "^0.2.0",
"validator": "^10.8.0"
},
"devDependencies": {
"dotenv": "^8.2.0",
"eslint": "^7.7.0",
"nodemon": "^2.0.6"
}
}
heroku logs --tail command gives following output:
I have tried every solution. But none of them seems to resolve the issue. Please, help.
UPDATE:
After I setup DB_URL in Heroku, it started working but I am getting another error.
Console:
1. GET https://capstone-ecommerce-backend.herokuapp.com/ 404 (Not Found)
2. Refused to load the image 'https://capstone-ecommerce-backend.herokuapp.com/favicon.ico' because it violates the following Content Security Policy directive: "default-src 'none'". Note that 'img-src' was not explicitly set, so 'default-src' is used as a fallback.
Try setting up the DB_URL in your Heroku application. Use the following command:
$ heroku config:set DB_URL=database_uri_here

How can I send file from postman to node js?

I want to upload file from postman to node js but I have problem.
POSTMAN
Write url,check post method,check form-data,check file,write file name and choose file
This is my code
app.js
const express = require('express');
const bodyParser = require('body-parser');
const fileUpload = require('express-fileupload');
app.use(fileUpload());
app.use(bodyParser.urlencoded({extended: false}));
app.use(bodyParser.json());
router.js
router.post('/schedule/entry', function(req,res){
console.log(req.file.name);
});
Console return me undefined name, if I write this code
router.post('/schedule/entry', function(req,res){
console.log(req.file);
});
Return 'undefined'
Why?
package.json
{
"name": "nodejs-rest-api-authentication",
"version": "1.0.0",
"description": "",
"main": "app.js",
"scripts": {
"start": "node server.js",
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "",
"license": "ISC",
"dependencies": {
"bcryptjs": "^2.4.3",
"body-parser": "^1.16.1",
"csv-array": "0.0.22",
"csv-write-stream": "^2.0.0",
"express": "^4.14.1",
"express-fileupload": "^0.3.0",
"fast-csv": "^2.4.1",
"formidable": "^1.1.1",
"json2csv": "^3.11.5",
"jsonwebtoken": "^8.1.0",
"mysql": "^2.15.0"
}
}
server.js
const app = require('./app');
const port = process.env.PORT || 3000;
const server = app.listen(port, function() {
console.log('Server listening on port ' + port);
});
screenshots
screenshots
codeGit
Based on the discussion in the comment section:
const express = require('express')
const app = express()
const formidable = require('formidable')
const path = require('path')
const uploadDir = '' // uploading the file to the same path as app.js
app.post('/', (req, res) =>{
var form = new formidable.IncomingForm()
form.multiples = true
form.keepExtensions = true
form.uploadDir = uploadDir
form.parse(req, (err, fields, files) => {
if (err) return res.status(500).json({ error: err })
res.status(200).json({ uploaded: true })
})
form.on('fileBegin', function (name, file) {
const [fileName, fileExt] = file.name.split('.')
file.path = path.join(uploadDir, `${fileName}_${new Date().getTime()}.${fileExt}`)
})
});
app.listen(3000, () => console.log('Example app listening on port 3000!'))
Attached Screenshots:
Because of body-parser middleware file will be not available in req so you must use another middleware libraries like connect-busboy or multer or connect-multiparty

Categories