loging response from server does not work - mongodb

I am following a tutorial from Coding Garden. There he writes to a database and sends it then back to the client.
When I try to do it, I do not get a respond from the server. I guess there has been a mix up in my code.
When I go to localhost/5000/posts there is no database. Why do I not get an errormessage, or a database?
Best regards
Expected Result:
https://youtu.be/JnEH9tYLxLk?t=3060
client code
const form = document.querySelector('form');
const loadingElement = document.querySelector(".loading");
const API_URL = "http://localhost:5000/posts";
loadingElement.style.display = "none";
form.addEventListener('submit', (event) => {
event.preventDefault();
const formData = new FormData(form);
const name = formData.get('name');
const content = formData.get('content');
const post = {
name,
content
};
form.style.display = "none";
loadingElement.style.display= "";
fetch(API_URL, {
method: "POST",
body: JSON.stringify(post),
headers: {
"content-type": "application/json"
}
}).then(response => response.json())
.then(createdPost => {
console.log(createdPost);
});
});
server code
const express = require("express");
const cors = require('cors');
const monk = require("monk");
const app = express();
const db = monk("localhost/posts");
const posts = db.get("posts");
app.use(cors());
app.use(express.json());
app.get("/", (req, res) => {
res.json({
message: "Post"
});
});
function isValidPost(post){
return post.name && post.name.toString().trim() !== "" &&
post.content && post.content.toString().trim() !=="";
}
app.post("/posts", (req, res) => {
if (isValidPost(req.body)){
const post = {
name: req.body.name.toString(),
content: req.body.content.toString(),
created: new Date()
};
//console.log(post);
posts
.insert(post)
.then(createdPost => {
res.json(createdPost);
});
}else {
res.status(422);
res.json({
message: "Hey, Titel und Inhalt werden benötigt!"
});
}
});
app.listen(5000, () => {
console.log('Listening on http://localhost:5000');
});

You forgot to handle the case when post.insert(...) fails and rejects. In this case no response is sent from your server and the request will hang. Add the following:
posts
.insert(post)
.then(createdPost => {
res.json(createdPost);
})
.catch(err => {
console.log(err);
res.status(500).json({errorMessage: err.message});
});

handle the fetch method with catch. It probably goes to catch.
fetch().then().catch(err => ...)

Related

Error: connect ECONNREFUSED 127.0.0.1:8000 in Express Js ( When try to Test with Postman )

I am really new to the industry and have this error when trying to check the database connection via API reuests with postman..... Please help me to settle this issue...
I just want to check the mongodb database by sendng API requests. Still I cannot identify the error and I am following a set of tutorials and occure this issue... Anyone can help me to identify the mistake it's highly appreciated....
{ this is dummy text to avoid please add more details...
Here is my code...
const app = express();
const { MongoClient } = require('mongodb');
const PORT = process.env.PORT || 8000;
// Initialize middleware
// we used to install body parser but now it's a built in middleware
// Function of express. It parses incoming JSONpayload
// app.use(express.json({extended:false}));
app.use(express.json({ extended: false }));
// Test Routs
// app.get("/", (req,res)=>res.send("Hello Aruna !!!"));
// app.post("/", (req,res)=>res.send(`Hello ${req.body.name} `));
// app.get("/hello/:name", (req.res)=>res.send(`Hello ${req.params.name}`))
app.get('/api/articles/:name', async (req, res) => {
try {
const articleName = req.params.name;
const client = await MongoClient.connect('mongodb://localhost:27017');
const db = client.db('mernblog');
const articlesinfo = db
.collection('articles')
.findOne({ name: articleName });
res.status(200).jason(articlesinfo);
client.close();
} catch (error) {
res.status(500).jason({ message: 'Error connecting to database', error });
}
});
app.post('/api/articles/:name/add-comments', (req, res) => {
const { username, text } = req.body;
const articleName = req.params.name;
articlesinfo[articleName].comments.push({ username, text });
res.status(200).send(articlesinfo[articleName]);
});
app.post('/', (req, res) => res.send(`Hello ${req.body.name}`));
app.get('/hello/:name', (req, res) => res.send(`Hello ${req.params.name}`));
app.listen(PORT, () => console.log(`Server is running at port ${PORT}`));
Server.js
Terminal
Error and API request in Postman
You have a typo in your code: jason should be json.
Other tips, you should handle your DB connection in a separate method and change your post request since articlesinfo is not a global variable:
const app = express();
const { MongoClient } = require('mongodb');
const PORT = process.env.PORT || 8000;
const client = new MongoClient('mongodb://localhost:27017');
const connectDB = async () => {
try {
await client.connect();
console.log('Successfully connected to DB')
} catch (err) {
await client.close();
console.log('Error connecting to DB');
process.exit(1);
}
}
// Initialize middleware
// we used to install body parser but now it's a built in middleware
// Function of express. It parses incoming JSONpayload
// app.use(express.json({extended:false}));
app.use(express.json({ extended: false }));
// Test Routs
// app.get("/", (req,res)=>res.send("Hello Aruna !!!"));
// app.post("/", (req,res)=>res.send(`Hello ${req.body.name} `));
// app.get("/hello/:name", (req.res)=>res.send(`Hello ${req.params.name}`))
app.get('/api/articles/:name', async (req, res) => {
try {
const articleName = req.params.name;
const db = client.db('mernblog');
const articlesinfo = db
.collection('articles')
.findOne({ name: articleName });
res.status(200).json(articlesinfo);
client.close();
} catch (error) {
res.status(500).json({ message: 'Error connecting to database', error });
}
});
app.post('/api/articles/:name/add-comments', (req, res) => {
const { username, text } = req.body;
const articleName = req.params.name;
const db = client.db('mernblog');
const articlesinfo = db
.collection('articles')
.updateOne({ name: articleName }, { $push: { comments: { username, text } } });
res.status(200).send(articlesinfo);
});
app.post('/', (req, res) => res.send(`Hello ${req.body.name}`));
app.get('/hello/:name', (req, res) => res.send(`Hello ${req.params.name}`));
connectDB();
app.listen(PORT, () => console.log(`Server is running at port ${PORT}`));

express session with connect-mongodb-session not getting cookies in browser but postman works well

i am getting set-cookie in response header but my browser does not use it.
also, the cookie is not sent to the server there every time a new session is made on server side due to this.
I have checked my routes on postman everything working as expected i.e : cookies are receive and sent by postman but the browser completely ignores cookies.
zip file of project
index.js
const express = require('express');
const session = require('express-session')
const cookieParser = require('cookie-parser');
const mongoDBStore = require('connect-mongodb-session')(session)
const routes = require('./routes/routes')
require('./model/model');
require('./db/mongoose')
const app = express();
const store = new mongoDBStore({
uri: 'mongodb+srv://mny:QTCdKtdkjfdjfouJJWbUYN#cluster0.zxfwd.mongodb.net/MernDocker?retryWrites=true&w=majority',
collection: "mySessions"
})
// app.use(cookieParser())
app.use(express.json());
// app.use(express.urlencoded({ extended: false }));
app.use((req, res, next) => {
res.header("Access-Control-Allow-Origin", req.headers.origin);
res.header("Access-Control-Allow-Headers", "*");
res.header("Access-Control-Allow-Credentials", 'true')//true as string
// res.header('Access-Control-Expose-Headers',
// 'Date, Etag, Access-Control-Allow-Origin, Set-Cookie, Access-Control-Allow-Credentials')
if (req.method === "OPTIONS") {
res.header("Access-Control-Allow-Methods", "GET,PATCH,POST,DELETE");
return res.status(200).send()
}
next();
});
app.use(session({
secret: "mny",
saveUninitialized: true,
cookie: {
path: "/",//if / the cookies will be sent for all paths
httpOnly: false,// if true, the cookie cannot be accessed from within the client-side javascript code.
secure: true,// true->cookie has to be sent over HTTPS
maxAge: 2*24 * 60 * 60 * 1000,
sameSite: 'none',//- `none` will set the `SameSite` attribute to `None` for an explicit cross-site cookie.
},
store: store,
resave: false,
}))
app.use(routes);
const port = process.env.PORT || 3001;
app.listen((port), (error) => {
console.log(`lisning on port ${port}`)
})
const express = require('express');
const User = require('../model/model');
const routes = express.Router();
/*
routes.get('/', async (req, res, next) => {
console.log('req.headers.cookie get')
console.log(req.headers.cookie)
// console.log(req.headers.cookie.split(';')[1].split('=')[1])
res.send({
"post": req.session.postClick,
"patch": req.session.patchClick
})
})*/
routes.post('/', async (req, res) => {
console.log("req.headers.cookie post method")
console.log(req.headers)
// console.log(req.headers.cookie.split(';')[1])
const user = new User(req.body)
try {
await user.save()
if (!req.session.postClick) {
req.session.postClick = 0
console.log(req.session);
}
req.session.postClick++
res.send({ "user": user, "postClick": req.session.postClick });
} catch (e) {
res.send(e)
}
})
module.exports = routes;
app.js frontend
import logo from './logo.svg';
import './App.css';
import { useState } from 'react';
const url = 'http://localhost:3001'
console.log(document.cookie)
function App() {
const [inputValue, setInputValue] = useState({
name: '',
})
const handleChange = (e) => {
const { name, value } = e.target;
setInputValue({
...inputValue,
[name]: value
})
}
const handleOnAdd = (e) => {
e.preventDefault()
console.log(document.cookie)
const addData = async () => {
try {
const res = await fetch(`${url}`, {
method: 'POST',
headers: {
"mode": 'cors',
"Credentials": 'include',
'Content-Type': 'application/json',
'Accept': 'application/json',
'WithCredentials': true,
},
body: JSON.stringify(inputValue)
})
if (res.ok) {
let d = await res.json()
console.log(d)
} else {
alert('fetch add failed')
}
} catch (e) {
console.log(e)
}
}
addData()
// setInputValue({})
}
return (
<div>
<h1>session with mongodb</h1>
<form className='form' >
<label>name</label>
<input
name='name'
onChange={(e) => handleChange(e)}
value={inputValue.name}
/>
<button onClick={handleOnAdd}>Add</button>
</form>
</div>
)
}
export default App;

How to make POST request using MongoDB?

I'm trying to make a POST request to my database. However, when I use Postman to test if the request is being made, it's giving me back an error,
Cannot POST /api/grocery
I'm using Model, View, Controller for my project. This is my index file
const express = require('express')
const app = express()
const port = 3000
const groceryController = require('./Controller/controllerGrocery.js')
app.use(express.urlencoded({extended: true}));
app.post('api/grocery', (req, res) => {
groceryController.addGrocery(req, res)
})
app.listen(port, () => {
console.log(`Example app listening at http://localhost:${port}`)
})
This is my controller file
const models = require('../Model/modelGrocery.js')
const addGrocery = (req, res) => {
const addGrocery = (err) => {
if (err) {
res.status(500).send()
} else {
res.status(201).end();
}
}
models.addGrocery(req.body, addGrocery)
}
module.exports = {
addGrocery: addGrocery
}
This is my model file that I'm connecting to the database
var db = require('../../DB/db.js');
const getGrocery = (doNext) => {
//query the database
db.find()
.then(result => doNext(null, result))
.catch(err => doNext(err))
//callback
}
const addGrocery = (grocery, callback) => {
db.insertOne({
item: grocery.item,
quantity: grocery.quantity
})
.catch(err => callback(err))
}
module.exports = {
addGrocery: addGrocery
}
Change API Path from api/grocery to /api/grocery
app.post('/api/grocery', (req, res) => {
groceryController.addGrocery(req, res)
})

Issues posting to my mongo database in react native

I am very new to React Native and I am trying to figure out how to connect my front end to my back end. I realize I may have my folder structure set up oddly but the connection works and I can fetch data from the database but when I attempt a post, it throws a 500 error. I cannot seem to figure out what is happening with it. If anyone has some insight I would greatly appreciate it. The post method console logs the req.body and "Here we are" in the controller file but fails immediately after that.
// index.js
require("dotenv").config();
const express = require("express");
const app = express();
const bodyParser = require("body-parser");
const morgan = require("morgan");
const { UserRoutes, TweetsRoutes } = require("./modules");
import dbConfig from "./config/db";
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(morgan("dev"));
// -----Database ----- \\
dbConfig(process.env.MONGO_DB_URL);
app.use((req, res, next) => {
res.header("Access-Control-Allow-Origin", "*");
res.header(
"Access-Control-Allow-Headers",
"Origin, X-Requested-With, Content-Type, Accept"
);
next();
});
app.use("/api", [UserRoutes, TweetsRoutes]);
// app.get("/", (req, res) => {
// res.send("endpoint live");
// });
const PORT = process.env.PORT || 3000;
app.listen(PORT, () => console.log(`Server listening on port ${PORT}🏄`));
// db.js
const mongoose = require("mongoose");
export default mongoURL => {
mongoose.Promise = global.Promise;
mongoose.connect(
mongoURL,
{ useNewUrlParser: true }
);
let db = mongoose.connection;
db.once("open", () => console.log("Connected to the database"));
db.on("error", console.error.bind(console, "Mongo connection error: "));
};
// tweetController.js
import Tweet from "./TweetsSchema";
module.exports = {
createTweet: async (req, res, next) => {
const createdTweet = req.body;
console.log("req.body: ", req.body);
try {
console.log("Here we are");
let tweet = await new Tweet.create(createdTweet);
tweet.save();
console.log("tweet: ", tweet);
res.status(201).json(tweet);
} catch (error) {
res.status(500).json({
error: true,
message: "There was an error creating the tweet"
});
}
},
getAllTweets: async (req, res, next) => {
const foundTweets = await Tweet.find({})
.lean()
.exec();
res.status(200).json(foundTweets);
next();
}
};
// actions.js
export const postTweet = tweet => {
let response = axios
.post(
`http://10.0.2.2:<PORT>/api/tweet`,
{ tweet },
{
headers: {
"Content-Type": "application/json;charset=UTF-8",
"Access-Control-Allow-Origin": "*"
}
}
)
.then(res => {
return res.data;
})
.catch(error => {
console.log(error);
});
return {
type: POST_TWEET,
payload: response
};
};
The problem is you mixed 2 commands for creating a new document
Instead of using both new and create like this:
let tweet = await new Tweet.create(createdTweet);
You should use only 1 of them like so:
let tweet = await Tweet.create(createdTweet);
tweet.save();
Or:
let tweet = new Tweet(createdTweet);
await tweet.save();

What is going wrong with my MongoDB API

For some reason my API is not working. An err response is being sent so I can narrow the problem down to the following code.
const express = require('express');
const router = express.Router();
const MongoClient = require('mongodb').MongoClient;
const ObjectID = require('mongodb').ObjectID;
const connection = (closure) => {
return MongoClient.connect('mongodb://localhost:27017/manatee', (err, db) => {
if (err) return console.log(err);
closure(db);
});
};
const sendError = (err, res) => {
response.status = 501;
response.message = typeof err == 'object' ? err.message : err;
res.status(501).json(response);
};
let response = {
status: 200,
data: [],
message: null
};
router.get('/tasks', (req, res) => {
connection((db) => {
db.collection('tasks').find()
.toArray()
.then((tasks) => {
response.data = tasks;
res.json(response);
})
.catch((err) => {
sendError(err, res);
});
});
});
module.exports = router;
I am using mongodb ^2.2.34 . Can anyone spot the problem here? I am pretty lost as to what it could be and any help would be much appreciated