MERN this same query different output from remote server - node.js

I have a problem with my MERN app. On my localhost everything is correct but since is hosted on remote server db return different data.
When I sent query http://:8080/getreports?date=40-2020
(actually whatever server get afte getreports? return always this same)
server return all records from db.
When I use this same query on localhost server return me records where date is equal to 40-2020.
(correct behave)
below me server code
Thanks for help
const express = require("express");
const bodyParser = require("body-parser");
const cors = require("cors");
const app = express();
const apiPort = process.env.PORT || 8080;
const path = require("path");
const Record = require("./models/record-model");
const db = require("./db");
app.use(bodyParser.urlencoded({ extended: true }));
app.use(cors());
app.use(bodyParser.json());
db.on("error", console.error.bind(console, "MongoDB connection error:"));
app.use(express.static(path.join(__dirname, "..", "build")));
app.get("/", function (req, res) {
res.sendFile(path.join(__dirname, "..", "build", "index.html"));
});
app.post("/reports", (req, res) => {
const body = req.body;
if (!body) {
return res.status(400).json({
success: false,
error: "You must provide a record",
});
}
const record = new Record(body);
if (!record) {
return res.status(400).json({ success: false, error: err });
}
record
.save()
.then(() => {
return res.status(201).json({
success: true,
message: "Record created!",
});
})
.catch((error) => {
return res.status(400).json({
error,
message: "Record not created!",
});
});
});
app.get("/getreports", async (req, res) => {
await Record.find({ "WW-YYYY": `${req.query.date}` }, (err, reports) => {
if (err) {
return res.status(400).json({ success: false, error: err });
}
if (!reports.length) {
return res
.status(404)
.json({ success: false, error: `Reports not found` });
}
return res.status(200).json({ success: true, data: reports });
}).catch((err) => console.log(err));
});
app.listen(apiPort, () => console.log(`Server running on port ${apiPort}`));

I want to shear solution for my problem. The problem was server couldn't recognize template string for parameter in html query. On local machine everything was ok but on remote server moongo behave default, like when you search empty object, return all records in database.
I just simple remove template string to simple variable and works, this is what i did in code:
await Record.find({ "WW-YYYY": ${req.query.date} }, (err, reports)
to
await Record.find({ "WW-YYYY": req.query.date }, (err, reports)
maybe this will help someone in future.
Regards,
Damian

Related

Node.js DELETE Request return wrong response

I'm making a DELETE request on my nodejs server, but the response is wrong.
When i try to send a DELETE request at my localhost server, it returns success: 0, message: "Record Not Found"
but when i go to check in the database, the parameters are gone
index.js
require("dotenv").config();
const express = require("express");
const app = express();
const userRouter = require("./api/users/user.router");
var cors = require('cors');
var corsOptions = {
origin: "http://localhost:3000"
};
app.use(cors(corsOptions));
app.use(express.json());
app.use("/api/", userRouter);
const port = process.env.PORT || 4000;
app.listen(port, () => {
console.log("server up and running on PORT :", port);
});
user.router.js
const router = require("express").Router();
const {
deleteUtenti
} = require("./user.controller");
router.delete("/", deleteUtenti);
module.exports = router;
user.controller.js
const {
deleteUtenti
} = require("./user.service");
module.exports = {
deleteUtenti: (req, res) => {
const data = req.body;
deleteUtenti(data, (err, results) => {
if (err) {
console.log(err);
return;
}
if (!results) {
return res.json({
success: 0,
message: "Record Not Found"
});
}
return res.json({
success: 1,
message: "user deleted successfully"
});
});
}
};
user.service.js
const pool = require("../../config/database");
module.exports = {
deleteUtenti: (data, callBack) => {
pool.query(
`delete from utenti where email = ?`,
[data.email],
(error, results, fields) => {
if (error) {
callBack(error);
}
return callBack(null, results[0]);
}
);
}
};
is it a problem of the code or of the server?
A few days ago the same thing happened to me with another function but to solve it was enough to recreate the table in the database, I tried to do the same thing but it didn't work
I Just found the problem, results[0] on user.service.js did not read the response from the database, so to do some tests I changed it to results where all the response from the database came out and I saw that I just had to take the affectedRows response from the database, so I changed it to results.affectedRows and now everything works as it should.

MongoDB returns 502 error in Vercel hosted app

I'm building a web app in next.js and hosting it on Vercel. I have set up a database cluster in MongoDB Atlas, which I can connect to in development (from localhost) and from MongoDB compass, but when I deploy it to Vercel, client.connect() gives me an HTTP 502 error.
Is there any reason why I can connect from localhost but not from my Vercel-deployed app? My connection string is mongodb+srv://<username>:<password>#testcluster.i2ddc.mongodb.net/data?retryWrites=true&w=majority as per the connection instructions on the Atlas dashboard.
Have you added Vercel ip to whitelist on Network Access configuration in MongoDb dashboard? You can try to add middleware to connect, and catch any error. I would also try without "retryWrites=true" in the connection string.
Middleware
import { MongoClient } from 'mongodb';
const client = new MongoClient(process.env.MONGODB_URI, {
useNewUrlParser: true,
useUnifiedTopology: true,
});
export default async function database(req, res, next) {
if (!client.isConnected()) await client.connect();
req.dbClient = client;
req.db = client.db(process.env.DB_NAME);
await setUpDb(req.db);
return next();
}
You just need to set up environmental variables.
This tutorial could be useful
Try this code may help.
const Express = require("express");
const BodyParser = require("body-parser");
const MongoClient = require("mongodb").MongoClient;
const ObjectId = require("mongodb").ObjectID;
const CONNECTION_URL = "mongodb+srv://id:password#portfolio.t6jry.mongodb.net/myinfo?retryWrites=true&w=majority";
const DATABASE_NAME = "info";
const port = process.env.PORT || 3000;
var app = Express();
app.use(BodyParser.json());
app.use(BodyParser.urlencoded({ extended: true }));
var database, collection;
app.listen(port, () => {
MongoClient.connect(CONNECTION_URL, { useNewUrlParser: true }, (error, client) => {
if(error) {
throw error;
}
database = client.db(DATABASE_NAME);
collection = database.collection("myinfo");
console.log("Connected to `" + DATABASE_NAME + "`!");
});
});
app.get("/", (req, res, next) => {
return res.json({ message: "Server Running" });
});
app.get("/info",async (request, response) => {
MongoClient.connect(CONNECTION_URL, { useNewUrlParser: true }, (error, client) => {client.db("info").collection("myinfo").find({}).toArray((error, result) => {
if(error) {
return response.json({ status: 500, message: "Internal Server Error" });
}
else if (!result) {
return response.json({ status: 422, message: "Document Not Found" });}
else{ return response.json({ status: 200, message: result});}
});
})
});
app.post("/postdata",async (request, response) => {
MongoClient.connect(CONNECTION_URL, { useNewUrlParser: true }, (error, client) => {client.db("info").collection("myinfo").find({}).toArray((error, result) => {
if(error) {
return response.json({ status: 500, message: "Internal Server Error" });
}
else if (!result) {
return response.json({ status: 422, message: "Document Not Found" });}
else{ return response.json({ status: 200, message: result});}
});
})
});

React state hooks work on development but not on build (production)

I developed a bug tracker app using MERN, and on local, the interface updates in real time when the user performs CRUD operations using react hooks (state) and react context.
But once I deployed my app on google cloud, it seemed to turn into a static website, and if I add,edit, or delete, I have to refresh the page to see the change.
What could be causing this to happen?
Here is my server.js code:
require("dotenv").config();
const express = require("express");
const app = express();
const bodyParser = require("body-parser");
const cors = require("cors");
const mongoose = require("mongoose");
const ticketRoutes = express.Router();
const PORT = 8080;
var path = require("path");
let Ticket = require("./ticket.model");
app.use(cors());
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
mongoose.connect(process.env.MONGO_DB, { useNewUrlParser: true, useUnifiedTopology: true }, (error) => {
console.log(error);
});
const connection = mongoose.connection;
connection.once("open", function () {
console.log("MongoDB database connection established successfully");
});
ticketRoutes.route("/").get(function (req, res) {
Ticket.find(function (err, tickets) {
if (err) {
console.log(err);
} else {
res.json(tickets);
}
});
});
ticketRoutes.route("/:id").get(function (req, res) {
let id = req.params.id;
Ticket.findById(id, function (err, ticket) {
res.json(ticket);
});
});
ticketRoutes.route("/add").post(function (req, res) {
let ticket = new Ticket(req.body);
ticket
.save()
.then((ticket) => {
res.status(200).json({ ticket });
})
.catch((err) => {
res.status(400).send("adding new ticket failed");
});
});
ticketRoutes.route("/delete/:id").delete(function (req, res) {
Ticket.findByIdAndRemove(req.params.id, function (err, ticket) {
if (err) {
console.log(err);
return res.status(500).send({ ticket });
}
return res.status(200).send({ ticket });
});
});
ticketRoutes.route("/update/:id").post(function (req, res) {
Ticket.findById(req.params.id, function (err, ticket) {
if (!ticket) res.status(404).send("data is not found");
else ticket.ticket_name = req.body.ticket_name;
ticket.ticket_status = req.body.ticket_status;
ticket
.save()
.then((ticket) => {
res.json({ ticket });
})
.catch((err) => {
res.status(400).send("Update not possible");
});
});
});
app.use("/tickets", ticketRoutes);
app.use(express.static(path.join(__dirname, "frontend/build")));
app.get("/*", (req, res) => {
res.sendFile(path.join(__dirname, "frontend/build/index.html"));
});
app.listen(process.env.port || 8080, () => {
console.log("Express app is running on port 8080");
});
The fix was very in depth, but basically my method of deployment to google cloud was a method that would only work with static web pages. I ended up deploying the app with heroku using this great guide: enter link description here

POST request not coming through (MERN)

I'm using the MERN stack to build an application for the first time.
In order to log HTTP requests I use "morgan".
I managed to send data to mongodb which seems to be working fine. The problem is that my post request is not coming through. It says "pending" for 4 minutes, then fails.
Here's what I think is the relevant part of my code:
"server.js":
const express = require("express");
const mongoose = require("mongoose");
const morgan = require("morgan");
const path = require("path");
const cors = require("cors");
const app = express();
const PORT = process.env.PORT || 8080;
const routes = require("./routes/api");
const MONGODB_URI =
"...";
mongoose.connect(MONGODB_URI || "mongodb://localhost/app", {
useNewUrlParser: true,
useUnifiedTopology: true
});
mongoose.connection.on("connected", () => {
console.log("Mongoose is connected.");
});
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cors());
app.use(morgan("tiny"));
app.use("/api", routes);
app.listen(PORT, console.log(`Server is starting at ${PORT}`));
Then I've put my routes into another file "api.js":
const express = require("express");
const router = express.Router();
const Lane = require("../models/lanes");
router.get("/", (req, res) => {
Lane.find({})
.then(data => {
res.json(data);
console.log("Get request successful!");
})
.catch(error => {
console.log("Error: ", error);
});
});
router.post("/save", (req, res) => {
const data = req.body;
const newLane = new Lane();
newLane.collection.insertMany(data, err => {
if (err) {
console.log(err);
} else {
console.log("Multiple docs inserted");
}
});
});
module.exports = router;
I'm using axios to send the request. This happens after submitting a form within my application.
reducer function:
const reducer = (state, action) => {
switch (action.type) {
case "add":
axios({
url: "http://localhost:8080/api/save",
method: "POST",
data: [...state, { id: uuid(), title: action.title, tasks: [] }]
})
.then(() => {
console.log("Data has been sent to the server");
})
.catch(() => {
console.log("Internal server error");
});
return [...state, { id: uuid(), title: action.title, tasks: [] }];
The reducer is being used by my context provider component, which looks like this:
export function LanesProvider(props) {
const [lanes, dispatch] = useReducer(reducer, defaultLanes);
return (
<LanesContext.Provider value={lanes}>
<DispatchContext.Provider value={dispatch}>
{props.children}
</DispatchContext.Provider>
</LanesContext.Provider>
);
}
The "add" method inside my reducer is being called when submitting a form inside another component.
Please let me know if I can add anything to my question that would help.
Thank you in advance!
you are not sending any response back to client. Try to modify post method like
router.post("/save", (req, res) => {
const data = req.body;
const newLane = new Lane();
newLane.collection.insertMany(data, err => {
if (err) {
console.log(err);
res.send(err)
} else {
console.log("Multiple docs inserted");
res.send("Multiple docs inserted")
}
});
});

MERN deployment issue heroku

I just started with backend and I am tying to deploy backend of my crud app but I am getting stuck for routes. After deploying on heroku I just get the part of app.get('/'). I can't find any router.get('/getData'.. or router.post('/updateData'..
here is the deployed heroku link:
for app.get('/'): https://vast-beyond-50574.herokuapp.com/
for router.get('/getData): https://vast-beyond-50574.herokuapp.com/getData
for router.post('/updateData'): https://vast-beyond-50574.herokuapp.com/updateData
Here is the code for backend server.js
const express = require('express');
var cors = require('cors');
const bodyParser = require('body-parser');
const logger = require('morgan');
const Data = require('./data');
const API_PORT = 3001;
const app = express();
app.use(cors());
const router = express.Router();
mongoose.connect(process.env.MONGODB_URI || 'mongodb://localhost/backend');
let db = mongoose.connection;
db.once('open', () => console.log('connected to the database'));
db.on('error', console.error.bind(console, 'MongoDB connection error:'));
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
app.use(logger('dev'));
router.get('/getData', (req, res) => {
Data.find((err, data) => {
if (err) return res.json({ success: false, error: err });
return res.json({ success: true, data: data });
});
});
router.post('/updateData', (req, res) => {
const { id, update } = req.body;
Data.findByIdAndUpdate(id, update, (err) => {
if (err) return res.json({ success: false, error: err });
return res.json({ success: true });
});
});
router.delete('/deleteData', (req, res) => {
const { id } = req.body;
Data.findByIdAndRemove(id, (err) => {
if (err) return res.send(err);
return res.json({ success: true });
});
});
router.post('/putData', (req, res) => {
let data = new Data();
const { id, message } = req.body;
if ((!id && id !== 0) || !message) {
return res.json({
success: false,
error: 'INVALID INPUTS',
});
}
data.message = message;
data.id = id;
data.save((err) => {
if (err) return res.json({ success: false, error: err });
return res.json({ success: true });
});
});
app.get('/', (req, res) => {
res.send('Deployed!');
});
app.use('/api', router);
const PORT = process.env.PORT || 3000
app.listen(PORT, () => console.log(`LISTENING ON PORT ${PORT}`));```
You're using your router inside the /api route (app.use('/api', router);) which means all of those routes will be prefixed with /api. So, you should be able to visit https://vast-beyond-50574.herokuapp.com/api/getData and see your data. (However, I tried this and got a different error, which you will have to debug separately).

Resources