How to POST and GET from mongoDB express server in react hooks? - node.js

I am getting an error to GET data from my API endpoint.
I am able to send data and also update/ delete them from the postTodo()method.
I have added it in a useEffect()so that the I am able to send data to server whenever a Todo is completed or deleted.
But whenever i reload the page, in the devtools, the todos array is [].
Some help would be appreciated.Thanks.
The Todo.jsx
const postTodo = (todos) => {
console.log(todos);
axios.post("http://localhost:4000/api/todos", todos, {
headers: {
"Content-Type": "application/json",
"Authorization": `Bearer ${token}`,
}
})
.then(res => {
console.log(res);
})
.catch(err => {
console.log(err);
})
}
useEffect(() => {
postTodo(todos)
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [todos])
useEffect(() => {
axios.get("http://localhost:4000/api/todos", {
headers: {
"Content-Type": "application/json",
"Authorization": `Bearer ${token}`,
}
})
.then(res => {
console.log(res);
setTodos(res.data.todos)
})
.catch(err => {
console.log(err);
})
}, [])
the server.js
const authCheck = (req, res, next) => {
if (req.headers['authorization']) {
const token = req.headers['authorization'].split(" ")
if (token[0] !== 'Bearer') {
return res.send({ status: 'error', error: 'invalid request' });
} else {
req.jwt = jwt.verify(token[1], process.env.jwtSECRET);
return next();
}
}
}
app.post("/api/todos", authCheck, async (req, res) => {
const todos = req.body
console.log(todos);
const { id } = req.jwt
const user = await User.findByIdAndUpdate(id, { "todos": todos })
// console.log(user);
})
app.get("/api/todos", authCheck, async (req, res) => {
const { id } = req.jwt
const user = await User.findById(id)
log(user) //user.todos is empty
res.send({
status: "ok", todos: user.todos })
})

You can try something like this, where use effect for todos will log the value everytime you create a new todo
const postTodo = (todos) => {
console.log(todos);
axios.post("http://localhost:4000/api/todos", todos, {
headers: {
"Content-Type": "application/json",
"Authorization": `Bearer ${token}`,
}
})
.then(res => {
console.log(res);
getTodos()
})
.catch(err => {
console.log(err);
})
}
const getTodos = () => {
axios.get("http://localhost:4000/api/todos", {
headers: {
"Content-Type": "application/json",
"Authorization": `Bearer ${token}`,
}
})
.then(res => {
console.log(res);
setTodos(res.data.todos)
})
.catch(err => {
console.log(err);
})
}
const newTodo = () => {
const allTodos = [...todos];
allTodos.push("new Todo at:" + new Date())
postTodo(allTodos)
}
useEffect(() => {
console.log('todo-list', todos)
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [todos])
useEffect(() => {
getTodos()
}, [])
return (<button onClick={() => }> Add Todo </button>)

The problem was solved,
actually it was the useEffect() issue.
I removed the UseEffect
and added the postTodos method after every useState hook updation.

Related

Mongoose React not filtering Users on age

I'm using React as front-end to display Filtered users on my website. Therefore I send a query to the backend (Mongoose) to filter users. But the problem is, Mongoose returns all the users instead of applying a filter.
export const getMembersGrid = (userId, token, seeking, minAge, maxAge, age) => {
return fetch(`${API}/members?minAge=${minAge}&maxAge=${maxAge}`, {
method: 'get',
headers: {
Accept: 'application/json',
'Content-Type': 'application/json',
Authorization: `Bearer ${token}`,
},
})
.then((response) => {
return response.json();
})
.catch((err) => console.log(err));
};
Mongoose:
exports.members = async (req, res) => {
let user = req.query.user ? req.query.user : 'asc';
let sortBy = req.query.sortBy ? req.query.sortBy : '_id';
let limit = req.query.limit ? parseInt(req.query.limit) : 6;
try {
let users = await User.find({
$and: [
{ minAge: { $gte: req.query.minAge } },
{ maxAge: { $lte: req.query.maxAge } },
],
})
.sort([[sortBy, user]])
.limit(limit);
return res.json(users);
} catch (err) {
return res.status(400).json({
error: 'users not found',
});
}
};
Sadly, I receive all the users and the filter is not working

My Access is blocked by cors policy but after a certain number of requests. It is working fine when I start the server. but after that it stops

So the problem is I am trying to access the backend of my application but it is getting blocked by the above message. It works for 4-5 requested once I restart my server. But after that, its requests are getting added to the pending list. I am using react for the frontend and node js with PostgreSQL for the backend. I am not sure why this problem is happening with the website.
error-msg :
Access to XMLHttpRequest at 'https://athrv-ed-demo.herokuapp.com/events' from origin 'https://arthv-ed-demo.netlify.app' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
Backend server code:
require("dotenv").config();
const express = require("express");
const app = express();
const cors = require("cors");
const port = process.env.PORT || 5000;
const routes = require("./routes");
const bodyParser = require("body-parser");
//middlewares
app.use(cors());
app.use(express.json());
app.use(require("morgan")("dev"));
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
app.use(function (req, res, next) {
res.setHeader("Access-Control-Allow-Origin", "*");
res.setHeader(
"Access-Control-Allow-Methods",
"GET, POST, OPTIONS, PUT, PATCH, DELETE"
);
res.setHeader("Access-Control-Allow-Credentials", true);
next();
});
//running the express app here
app.use("/", routes);
app.listen(port, () => {
console.log(`My app is running at ${port}`);
});
Here is the front-end code from where I am making the calls. The same thing is happening with both API.
const axios = require("axios");
const url = "http://localhost:5000";
// const url = "https://athrv-ed-demo.herokuapp.com";
export async function getevents() {
console.log("Preload triggered at index");
return await axios({
url: `${url}/events`,
method: "GET",
headers: {
mode: "no-cors",
Accept: "application/json",
},
})
.then((response) => {
// console.log("events recieved, From axios");
// console.logponse.data);
return response.data;
})
.catch((err) => {
// console.log("events not recieved, error in axios" + err);
return false;
});
}
export async function eventedit(event) {
// console.log("edit event is clicked");
return await axios({
url: `${url}/eventedit/${isAuthenticated().user.uid}/${event.eid}`,
method: "PUT",
headers: {
mode: "no-cors",
Accept: "application/json",
Authorization: `Bearer ${isAuthenticated().token}`,
},
})
.then((response) => {
// console.log("view toggled !, From axios");
// console.log(response.data);
return response.data;
})
.catch((err) => {
// console.log("view couldn't be toggled, error in axios" + err);
return false;
});
}
export async function getlist(event) {
return await axios({
url: `${url}/getlist/${isAuthenticated().user.uid}/${event.eventno}`,
method: "GET",
headers: {
mode: "no-cors",
Accept: "application/json",
Authorization: `Bearer ${isAuthenticated().token}`,
},
})
.then((response) => {
// console.log("got all peoples !, From axios");
// console.log(response.data);
return response.data;
})
.catch((err) => {
console.log("couldn't get all people, error in axios" + err);
return false;
});
}
export async function register(user) {
return await axios({
url: `${url}/registration`,
method: "POST",
data: {
name: user.name,
age: user.age,
phone: user.phone,
email: user.email,
college: user.college,
eventno: user.eventno,
},
headers: {
mode: "no-cors",
Accept: "application/json",
"Content-Type": "application/json",
},
})
.then((response) => {
// console.log("registration done!, From axios");
// console.log(response.data);
return response.data;
})
.catch((err) => {
// console.log("registration not done, error in axios" + err);
return false;
});
}
export async function signin(user) {
return await axios({
url: `${url}/signin`,
method: "POST",
data: {
email: user.email,
password: user.password,
},
headers: {
mode: "no-cors",
Accept: "application/json",
"Content-Type": "application/json",
},
})
.then((response) => {
// console.log("data from axios and signin successfull ");
// console.log(response.data);
return response.data;
})
.catch((err) => {
// console.log(user.password + " " + user.email);
// console.log("Error in axios {email and password doesn't match}");
return false;
});
}
export const signout = () => {
if (typeof window !== "undefined") {
localStorage.removeItem("jwt");
return axios({
url: `${url}/signout`,
method: "GET",
})
.then((response) => {
console.log("Signout Successfull from Axios");
})
.catch((err) => {
console.log(err);
});
}
};
export async function postevent(event) {
return await axios({
url: `${url}/postevent/${isAuthenticated().user.uid}`,
method: "POST",
data: {
name: event.name,
date: event.date,
},
headers: {
mode: "no-cors",
Accept: "application/json",
Authorization: `Bearer ${isAuthenticated().token}`,
},
})
.then((response) => {
// console.log("new event posted!, From axios");
// console.log(response.data);
return response.data;
})
.catch((err) => {
// console.log("Couldn't post, error in axios" + err);
return false;
});
}
export const authenticate = (data, next) => {
if (typeof window !== "undefined") {
localStorage.setItem("jwt", JSON.stringify(data));
next();
}
};
export const isAuthenticated = () => {
if (typeof window == "undefined") {
return false;
}
if (localStorage.getItem("jwt")) {
return JSON.parse(localStorage.getItem("jwt"));
} else {
return false;
}
};

Failed to execute 'fetch' on 'Window': Invalid value

I'm building a login system using NodeJS, but occurer this error on console when i click on my button to login, can anyone help me to solve?, It's saying that is a invalide value on fetch.
firebase.auth().signInWithEmailAndPassword(login, password)
.then(({ user }) => {
return user.getIdToken().then((idToken) => {
return fetch("/sessionLogin", {
method: "POST",
headers: {
Accept: "application/json",
"Content-Type": "application/json",
"CSRF-Token": Cookies.get("XSRF-TOKEN"),
},
body: JSON.stringify({ idToken }),
});
});
})
.then(() => {
return firebase.auth().signOut();
})
.then(() => {
window.location.assign("/profile");
});
return false;
});
app.post("/sessionLogin", (req, res) => {
const idToken = req.body.idToken.toString();
const expiresIn = 60 * 60 * 24 * 5 * 1000;
admin
.auth()
.createSessionCookie(idToken, { expiresIn })
.then(
(sessionCookie) => {
const options = { maxAge: expiresIn, httpOnly: true };
res.cookie("session", sessionCookie, options);
res.end(JSON.stringify({ status: "success" }));
},
(error) => {
res.status(401).send("UNAUTHORIZED REQUEST!");
}
);
});
Check your app.js File -->
app.all("*", (req, res, next) => {
res.cookie("XSRF-TOKEN", req.csrfToken());
next();
});
Make sure you call the csrfToken Function (given in line 2).

How to fetch a specific field from axios post API request

I am using the below piece of code
const axios = require('axios')
axios
.post('https://xxx', {
"audience": "http://xxxx",
"grant_type": "xxxxx",
"client_id": "xxxxx",
"client_secret": "xxxxx"
})
.then(res => {
console.log(res)
})
.catch(error => {
console.error(error)
})
And I wanted assign the "res.data.token" to a variable token and use the variable in below code
describe('/GET device information', function () {
it("it should GET a Good Auth Status", function(done) {
chai.request('http:xxxxxx')
.get('xxxxxxxxxxxx')
.set({ "Authorization": `Bearer ${token}` })
.then((res) => {
(res).should.have.status(200);
// console.log(body) - not really needed, but I include them as a comment
done();
}).catch((err) => done(err))
});
})
you could wrap it in a try/catch and destructure the object:
try {
const res = await axios.post('https://xxx', {
'audience': 'http://xxxx',
'grant_type': 'xxxxx',
'client_id': 'xxxxx',
'client_secret': 'xxxxx'
})
const { data, token, foo, bar, status } = res.data
(status).should.equal(200)
} catch(e) {
console.log(e)
}
}
quick example

req.session is not persistent on browser?

So I have a very typical query.
I am new to this and I am building a simple login web app using node and express-session which are stored in MongoDB.
Here is my code:
sessionRouter.post("", async(req, res) => {
try {
const user = await User.findByCredentials(
req.body.email,
req.body.password
);
if (user) {
const sessionUser = sessionizeUser(user);
req.session.user = sessionUser;
console.log(req.session.id);
res.send(req.session.user);
} else {
throw new Error("invalid details.");
}
} catch (e) {
res.status(400).send(e);
}
});
//route to logout
sessionRouter.delete("", ({
session
}, res) => {
try {
const user = session.user;
if (user) {
console.log(session.id);
session.destroy((err) => {
if (err) console.log(err);
res.clearCookie(process.env.SESS_NAME);
res.send(session.id);
});
} else {
throw new Error("Something went wrong");
}
} catch (err) {
console.log("things went wrong!");
//res.status(422).send(JSON.stringify(err));
}
});
I am storing a 'user' attribute to req.session when I call the login API but when I call the logout API it generates a totally new session!.
Things go smoothly when I use postman to call these endpoints but when using a browser nothing works.
These are the calling functions I am using in browser:
const loggerin = () => {
var myHeaders = new Headers();
myHeaders.append("Content-Type", "application/json");
myHeaders.append("Connection", "keep-alive");
var raw = JSON.stringify({
email: "xxxxxxxxxx",
password: "xxxxxx",
});
var requestOptions = {
method: "POST",
headers: myHeaders,
body: raw,
redirect: "follow",
};
fetch("http://localhost:3001/api/session", requestOptions)
.then((response) => response.text())
.then((result) => console.log(result))
.catch((error) => console.log("error", error));
};
const loggerout = () => {
var myHeaders = new Headers();
myHeaders.append("Content-Type", "text/plain");
myHeaders.append("Connection", "keep-alive");
var requestOptions = {
method: "DELETE",
};
fetch("http://localhost:3001/api/session", requestOptions)
.then((response) => response.text())
.then((result) => console.log(result))
.catch((error) => console.log("error", error));
};
const test = () => {
var myHeaders = new Headers();
myHeaders.append("Content-Type", "text/plain");
myHeaders.append("Connection", "keep-alive");
var requestOptions = {
method: "GET",
};
fetch("http://localhost:3001/api/session", requestOptions)
.then((response) => response.text())
.then((result) => console.log(result))
.catch((error) => console.log("error", error));
};
Please help!!! Thanks in advance!
The issue was that I was creating the session in the wrong function. I corrected that and it worked.

Resources