Failed to execute 'fetch' on 'Window': Invalid value - node.js

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).

Related

or: Cannot read properties of undefined (reading 'email')

I am sending an auth request from chrome to my backend, there is payload chrome developer tool, it seems to have received the object, but I am backend
or: Cannot read properties of undefined (reading 'email')
It gives an error, I printed req.body from the console, it is empty object, what can I do?
backend
postmande works fine and logs in successfully
const { body: { user } } = req
console.log(req.body)
const userLogin = new User();
if (!user.email && !user.password) {
return res.status(402).json({
errors: "Eposta veya şifre zorunlu 😊 ! ",
});
}
return passport.authenticate('local', {
session: false,
successRedirect: '/home',
failureRedirect: '/login'
}, (err, passportUser, info) => {
if (err) {
return next(err)
}
if (passportUser) {
console.log(passportUser)
const user = passportUser
user.token = userLogin.generateJWT(user.email, user.id);
return res.json({ user: passportUser })
}
return res.status(400).json({ message: info });
})(req, res, next)
react fetch (client)
const [email, setEmail] = useState("")
const [password, setPassword] = useState("")
// const token = localStorage.getItem("X-CSRF-TOKEN");
const loginProccsess = async (e) => {
e.preventDefault()
const data = {
"user": {
email,
password
}
}
fetch("/api/auth/login", {
method: "POST",
mode: "cors",
// credentials: "some-origin",
header: {
"Content-type ": "application/json"
},
redirect: "follow",
body: JSON.stringify(data)
}).then((res) => {
console.log(res)
})
.catch(err => console.log(err))
}

Post request from client gives undefined (nodejs)

I'm doing clienten post operation on my node js server, it works fine from postman, but clienten undefend returns
as i said from postman
{ "user": {
"email": "levlaaaaa#levla.com",
"password": "123" } }
When I throw the object, it works fine, but it returns undefined on the cilient side.
client request file (react)
const loginProccsess = async (e) => {
e.preventDefault()
const data = {
"user": {
"email":email,
"password": password
}
}
// return console.log(JSON.stringify(data))
await fetch("/api/auth/login", {
method: "POST",
mode: "cors",
// credentials: "some-origin",
header: {
"Content-type ": "application/json"
},
redirect: "follow",
body: JSON.stringify(data)
}).then((res) => {
console.log(res)
})
backend login.js (login router request)
router.post("/login", authOP, (req, res, next) => {
const { body: { user } } = req
const userLogin = new User();
console.log(user)
if (!user.email && !user.password) {
return res.status(402).json({
errors: "Eposta veya şifre zorunlu 😊 ! ",
});
}
return passport.authenticate('local', {
session: false,
successRedirect: '/home',
failureRedirect: '/login'
}, (err, passportUser, info) => {
if (err) {
return next(err)
}
if (passportUser) {
console.log(passportUser)
const user = passportUser
user.token = userLogin.generateJWT(user.email, user.id);
return res.json({ user: passportUser })
}
return res.status(400).json({ message: info });
})(req, res, next)
})
// app.js(server) (main file)
app.use(Sentry.Handlers.requestHandler());
app.use(cookieParser());
app.use(express.json())
app.use(cors());
app.use(session({
resave: false,
saveUninitialized: true,
secret: 'secret'
}))
app.use(passport.initialize())
app.use(passport.session())

How to POST and GET from mongoDB express server in react hooks?

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.

CORS express js dont save a cookie

I read a lot of questions like this but no one is usefull for me.
I have a MERN app. I use Heroku to deploy. In my local environent everithing works but in heroku the login crash. I use Cookies. and try every posible configuration.
Please help.
This is my login server:
login: async (req, res) => {
try {
const { email, password } = req.body;
const user = await Users.findOne({ email })
//console.log(user)
if (!user) return res.status(400).json({ msg: "Usuario inexistente" })
const isMatch = await bcrypt.compare(password, user.password)
if (!isMatch) return res.status(400).json({ msg: "Clave erronea" })
//If login success, craete access Token and refresh
const accesstoken = createAccessToken({ id: user._id })
const refreshtoken = createRefreshToken({ id: user._id })
//console.log(refreshtoken)
res.cookie('refreshtoken', refreshtoken, {
sameSite: 'strict',
httpOnly: true,
path: '/user/refresh_token',
maxAge: 7 * 24 * 60 * 60 * 1000 //7days
})
res.json({ accesstoken })
} catch (err) {
return res.status(500).json({ msg: err.message })
}
},
Here server conf.
//MIDDELEWARES
app.use(express.json())
app.use(cookieParser())
//app.use(cors())
/*app.use(cors({
credentials: true,
origin: 'https://gabymanualidades.herokuapp.com/'
}))*/
app.use(cors({origin: 'https://*****.herokuapp.com', methods: ['POST', 'PUT', 'GET', 'OPTIONS', 'HEAD'], credentials: true, headers: 'Authorization, X-API-KEY, Origin, X-Requested-With, Content-Type, Accept, Access-Control-Allow-Request-Method' }))
app.use(fileUpload({
useTempFiles: true
}))
And client:
const loginSubmit = async e => {
e.preventDefault()
try {
//await axios.post('/user/login', { ...user })
const res=await axios.post('/user/login', { ...user }, {
headers: {
'Content-Type': 'application/json'
},
withCredentials: true,
baseURL: "*****.herokuapp.com"
})
console.log(res)
localStorage.setItem('firstLogin', true)
//window.location.href = "/products";
} catch (err) {
alert(err.response.data.msg)
}
}
Thak you very much!
Screenshot:
It is as if I logged in without saving the cookie since then I can't get it again here:
useEffect(() => {
const firstLogin = localStorage.getItem('firstLogin')
if (firstLogin) refreshToken()
}, [])
const refreshToken = async () => {
try {
console.log("aca problema")
const res = await axios.get('/user/refresh_token', {
headers: {
'Content-Type': 'application/json'
},
withCredentials: true,
baseURL: "https://young-wildwood-03509.herokuapp.com/"
})
setToken(res.data.accesstoken)
setTimeout(() => {
refreshToken()
}, 10 * 60 * 1000)
} catch (err) {
alert(err.response.data.msg)
}
}
Server:
refreshToken: (req, res) => {
try {
//console.log(req.cookies)
const rf_token = req.cookies.refreshtoken;
if (!rf_token) return res.status(401).json({ msg: "Plase Login or registeer" })
jwt.verify(rf_token, process.env.REFRESH_TOKEN_SECRET, (err, user) => {
if (err) return res.status(400).json({ msg: "Plase Login or registerr" })
const accesstoken = createAccessToken({ id: user.id })
//res.json({user, accesstoken})
console.log({ accesstoken })
res.json({ accesstoken })
})
//res.json({ rf_token })
} catch (err) {
return res.status(500).json({ msg: err.message })
}
},

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

Resources