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).
Related
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
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});}
});
})
});
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
On localhost:5000/posts my data is successfully showing but if I do the same thing in Heroku: https://rest-in-peep.herokuapp.com/posts I get an application error. https://rest-in-peep.herokuapp.com/ works fine and I deployed it through Heroku GIT. I made sure to config my environmental vars in Heroku and added a Procfile but I am still getting this application error. I've been trying all day to figure this out but what I expect to happen is if I type in https://rest-in-peep.herokuapp.com/posts, I will get all the data that is being stored on my MongoDB database.
app.js file
const http = require("http");
const express = require("express");
const mongoose = require("mongoose");
const bodyParser = require("body-parser");
const cors = require("cors");
require("dotenv/config");
const app = express();
const server = http.createServer(app);
//Middlewares
app.use(cors());
app.use(bodyParser.json());
//Import Routes
const postsRoute = require("./routes/posts");
app.use("/posts", postsRoute);
//ROUTES
app.get("/", (req, res) => {
res.send("We are on home");
});
//Connect to DB
mongoose.connect(
process.env.DB_CONNECTION,
{ useNewUrlParser: true },
() => console.log("connected to MongoDB")
);
//How do we start listening to the server
server.listen(process.env.PORT || 5000, () => {
console.log("App now running on PORT");
});
routes>
posts.js
const express = require("express");
const Post = require("../models/Posts");
const router = express.Router();
//GETS BACK ALL THE POSTS
router.get("/", async (req, res) => {
try {
const posts = await Post.find();
res.json(posts);
} catch (err) {
res.json({ message: err });
}
});
//SUBMITS A POST
router.post("/", async (req, res) => {
console.log(req);
const post = new Post({
quote: req.body.quote
});
try {
const savedPost = await post.save();
res.json(savedPost);
} catch (err) {
res.json({ message: err });
}
});
//SPECIFIC POST
router.get("/:postId", async (req, res) => {
try {
const post = await Post.findById(req.params.postId);
res.json(post);
} catch (err) {
res.json({ message: err });
}
});
//Delete Post
router.delete("/:postId", async (req, res) => {
try {
const removedPost = await Post.remove({ _id: req.params.postId });
res.json(removedPost);
} catch (err) {
res.json({ message: err });
}
});
//Update a post
router.patch("/:postId", async (req, res) => {
try {
const updatedPost = await Post.updateOne(
{ _id: req.params.postId },
{
$set: { quote: req.body.quote }
}
);
res.json(updatedPost);
} catch (err) {
res.json({ message: err });
}
});
module.exports = router;
gitignore
/node_modules
models>Posts.js
const mongoose = require("mongoose");
const PostSchema = mongoose.Schema({
quote: {
type: String,
required: true
}
});
module.exports = mongoose.model("Posts", PostSchema);
I'm new at using back-end code.
I'm trying to Insert basic line into MongoDB online DB.
These are my files:
server.js:
const express = require('express');
const MongoClient = require('mongodb').MongoClient;
const bodyParser = require('body-parser');
const app = express();
var db = require('./config/db');
const port = 8000;
app.use(bodyParser.urlencoded({ extended: true }));
MongoClient.connect(db.url, (err, database) => {
if (err) return console.log(err);
db = database.db('note-api');
require('./app/routes')(app, db);
require('./app/routes')(app, database);
app.listen(port, () => {
console.log('We are live on ' + port);
});
})
note_routes.js:
module.exports = function (app, db) {
// const collection =
app.post('/notes', (req, res) => {
const note = { text: req.body.body, title: req.body.title };
db.collection('notes').insert(note, (err, result) => {
if (err) {
res.send({ 'error': err });
} else {
res.send(result.ops[0]);
}
});
});
};
db.js:
module.exports = {
url: "mongodb://laelav:laelav1#ds227594.mlab.com:27594/getremp"
};
Whenever i try using POST and wish to update the online DB - I get an unauthorized error:
unauthorized error
Then I added this line in note_routes.js:
db.grantRolesToUser("laelav", [{ role: "readWrite", db: "getremp" }]);
And got the following "TypeError: db.grantRolesToUser is not a function":
not a function error
Please help!