Express router working fine locally but not on heroku - javascript

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}`);
});

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)

Unable to connect mongoDb to Express

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`);
}
});

Node Js TypeError with morgan: app.use is not a function

I am new to node js and following a tutorial on scotch.io. I've imported morgan for logging requests, but when I run the code I get TypeError: app.use is not a function. This is my code for app.js;
const express = require('express');
const logger = require('morgan');
const bodyParser = require('body-parser');
const app = express;
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.get('*', (req, res) => res.status(200).send({
message: 'Welcome to deep thinking.'
}));
module.exports = app;
And for package.json:
{
"name": "postgres-express-react-node-tutorial",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"start:dev": "nodemon ./bin/www",
"test": "echo \"Error: no test specified\" && exit 1"
},
"keywords": [],
"author": "",
"license": "ISC",
"dependencies": {
"body-parser": "^1.18.3",
"express": "^4.16.3",
"morgan": "^1.9.1"
},
"devDependencies": {
"nodemon": "^1.18.4"
}
}
require('express') returns a function, which you should call in order to get the express application. Therefore:
const app = express;
should be changed to:
const app = express();
Try this, change app=express; to app=express();
const express = require('express');
const logger = require('morgan');
const bodyParser = require('body-parser');
const app = express(); // changed this line
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.get('*', (req, res) => res.status(200).send({
message: 'Welcome to deep thinking.'
}));
module.exports = app;

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

Express .post routing method undefined

I'm new to nodejs and express and I can't seem to phantom as per why this method isn't resolved in Webstorm. The .get method returns fine, testing it with the .all method works fine aswell. I have no clue why the .post method is unresolved, node starts up fine but if I try to send a post request to it through Postman it just gives an error:
the Postman error
app.js
'use strict';
var express = require("express");
var bodyParser = require("body-parser");
var app = express();
var routes = require("./routes");
app.use(function (req, res, next) {
console.log(`${req.method} ${req.originalUrl}`);
next();
});
app.use(bodyParser.json());
app.use("/questions", routes);
// routes(app);
var port = process.env.PORT || 3000;
app.listen(port, function () {
console.log("Express is running at", port);
});
routes.js
'use strict';
var express = require("express");
var router = express.Router();
// GET /questions
// Route for getting all questions
router.get("/", function (req, res) {
res.json({
response: "You sent me an awesome GET request, thank you!"
});
});
// POST /questions
// Route for creating a question
router.post("/questions", function (req, res) {
res.json({
response: "You sent me an awesome POST request, thank you!"
});
body: req.body;
});
module.exports = router;
package.json
{
"name": "02-express-api",
"version": "1.0.0",
"description": "",
"main": "app.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"keywords": [],
"author": "",
"license": "ISC",
"dependencies": {
"body-parser": "^1.15.2",
"express": "^4.13.4"
}
}
router.post("/questions", should be router.post("/", for this to work; right now, that handler is responding to the URI /questions/questions since the router itself gets attached to handle URIs under /questions.

Categories