Reputation: 2106
I have a backend server using express.js I use react for my front end, so when I log in, the cookie will be saved in the browser but for some reason the session is not persisted and when I try to access some information from some route that requires authentication it will deny the access. I use postman to login and it will persist the session with no problem and can access routes that require authentication, so there must be a problem in the front end that it will not be created here's my codes:
Backend:
var cors = require('cors')
app.use(cors({
origin: 'http://localhost:3000',
methods: ['POST', 'PUT', 'GET', 'OPTIONS', 'HEAD'],
credentials: true
}));
Front end:
const postData = () => { //this is for login
const requestBody = {
username: name,
password: password,
};
const config = {
headers: {
"Content-Type": "application/x-www-form-urlencoded",
},
withCredentials: true,
accept: "application/json",
};
axios
.post(`${myUrl}/login`, qs.stringify(requestBody), config)
.then((res) => {
console.log(res.data);
})
.catch((e) => {
console.log(e);
});
};
const getData = async () => { //to access some data that requires authentication
axios
.get(`${myUrl}/edit`)
.then((res) => {
console.log(res.data);
})
.catch((e) => {
console.log(e);
});
};
when I log in with my front end I get a success message that I put (successfully logged in) so that means there is no problem with the post request and the CORS there's only one problem which is the front-end, what might be the problem?
PS: what's so interesting is that the cookie is actually saved in the browser but when I try to access some information that requires authentication it denies access!
Upvotes: 1
Views: 523
Reputation: 46
try to put the credentials to true in the get request as well:
const getData = async () => { //to access some data that requires authentication
axios
.get(`${myUrl}/edit`, { withCredentials: true })
.then((res) => {
console.log(res.data);
})
.catch((e) => {
console.log(e);
});
};
Upvotes: 3