not able to send request to express server using axios - javascript

I am building a chat application like whatsapp, & implementing the feature - when user clicks on any person's name, his chats appears, but can't able to send request to server when user clicks
Source code
There is div, when user will click on it, it will fetch data from server (onclick event handler) in Sidebar.js file -
{friends.map((e) => (
<div
onClick={getChatDetails}
key={e.friendName}
className='sidebar_chat_info'>
<Avatar />
<div>
<h2>{e.friendName}</h2>
<p>{getLastMessage()}</p>
</div>
</div>
))}
this is getChatDetails function in sidebar.js file
const getChatDetails = (e) => {
//console.log(e.target.textContent);
const Myfriend = e.target.textContent;
axios
.post('http://localhost:2000/message/get', { friend: Myfriend })
.then((response) => {
console.log(response);
})
.catch((error) => console.log(error));
};
At the server side , this is route in index.js file
Server is running on port 2000
app.post('/message/get', isloggedIn, async (req, res) => {
console.log('REQUESTED!');
try {
const conversation = await req.user.MyConversation.find(
(element) => element.friendName == req.body.friend
);
const messages = await conversationModel.findById(conversation.chats);
res.send(messages);
//await MessageModel.remove({})
} catch (error) {
res.status(500).send(error);
}
});
This is error on browser console , when I am clicking on div
But when I am sending request through postman, I am getting response
When I am sending request in other files (login.js), it's working there, don't know why it is not working only Sidebar.js file

The issue that you're having is that e in getChatDetails is undefined. The reason for this is is onclick does not pass an event object. In order to pass an event object to your sidebar function, you need to attach an event listener to it, which is a bit better than using onclick in most cases anyways (imo). Something like this:
const sidebar = document.getElementsByClassName('sidebar_chat_info')
for (let i = 0; i < sidebar.length; i++) {
sidebar[i].addEventListener('click', handleClick = e => {
//console.log(e.target.textContent);
const Myfriend = e.target.textContent;
axios
.post('http://localhost:2000/message/get', { friend: Myfriend })
.then((response) => {
console.log(response);
})
.catch((error) => console.log(error));
})

The middleware "isLoggedIn" causing issue. The problem was in my authentication part, when the user has been logged in then only he will see home page
index.js file at line 113
I added console.log and found that "NOT LOGGED IN " is displayed
function isloggedIn(req, res, next) {
if (req.isAuthenticated()) {
return next();
} else {
console.log('NOT LOGGED IN !');
res.status(500).send('DENIED PERMISSION!');
}
}
I think it is happening because after logging in , I am redirecting to home page from
Login.js at line 59
history.push('/', { user: response.data });
const submitForm = async (e) => {
e.preventDefault();
axios
.post('http://localhost:2000/login', {
username: username,
password: password,
})
.then((response) => {
history.push('/', { user: response.data });
})
.catch((error) => setIsError(true));
//console.log(user.data); //user.data contains the details
//CALLING THE HOME PAGE AFTER SIGNUP & SENDING DETAILS OF CURRENT USER THERE !
//history.push('/', { user: user.data });
};
Maybe the request will be authenticated only from Login.js file, but I can't make other request from this file like getting chats details, sending message etc. I will have to go to home page . That's why I am redirecting to home page after logging in
On home page my request is not authenticated.
In postman all routes are working as I am not switching pages.
Login and logout routes are working as they are not taking in account "isLoggedIn"
Please suggest how to work with routes that needs authentication, like send message, gettingchats details?
PS - My request is even not authenticated from Login.js. After logging in, this time I didn't redirect to home page. I made request to route that needs authentication after logging in , it's still showing "NOT LOGGED IN" on server

Related

res.redirect not workig when working with React

I am using react as frontend and made api using express I have the following code I have stored jwt token in the cookies while logging in for the first then when trying to login in again I check if there is already a token in the cookies if there is token in the cookie (currently I am not verifying it I just want it to work) redirect the user to profile page but it doesn't work.
Although an XMLHttpRequest can be seen in the network tab (click for screenshot) but it doesn't work.
PS - I am using Axios in the frontend to make a get request.
loginRouter.get("/", async (req, res) => {
try {
const cookieFound = req.cookies["login-token"];
if (cookieFound) {
res.redirect("profile");
} else {
res.redirect("login");
}
} catch (error) {
console.log(error);
res.status(500).json("Ooops something went wrong!");
}
});
code to make a get request in the frontend
useEffect(() => {
Axios.get("/login");
}, []);
EDIT :-
Backend
loginRouter.get("/", async (req, res) => {
try {
const cookieFound = req.cookies["login-token"];
if (cookieFound) {
res.send("/profile");
}
// res.status(200).json(cookieFound);
} catch (error) {
console.log(error);
res.status(500).json("Ooops something went wrong!");
}
});
Client
useEffect(() => {
const alreadyLoggedIn = async () => {
const url = await Axios.get("/login");
window.location = url.data;
};
alreadyLoggedIn();
}, []);
To what you have entered I think you should change window.location = url.data to window.location = window.location.hostname + url.data;
In your current setup the total url will be set to /profile while you want yourwebsite.com/profile

Shopify REST API Pagination using Node.js and Express

I'm facing an issue, using Product resource on Shopify REST Api : I need to display many products on a Node.js Express app, I've left the default limit at 50 and when I want to fetch the next page of 50 products when I click on a next or previous button (I use the nextPageUrl/prevPageUrl from the response headers) I get a 401 error if the request is made from the client-side because of CORS error
Then I tried to make the request on server-side, I've passed the link from client to server when hitting the next button for example but it still does not work
The documentation is not clear at all about the paginated request and nothing that i've done from the documentation now is correct, it just says "Make a GET request to the link headers" and voila
Anyone have done this before ?
Code below
protectedRouter.get('/inventory', async (req, res) => {
try {
const session = await Shopify.Utils.loadCurrentSession(req, res);
const client = new Shopify.Clients.Rest(session.shop, session.accessToken)
const result = await client.get({
path: 'products',
})
res.render('inventory', {
products: result,
})
} catch (error) {
throw error;
}
});
script(src="/scripts/pagination.js")
div.View
h3.title.my-4 Etat des stocks
div.row
div.col-6
span(id='previousLink') #{products.pageInfo.prevPageUrl ? products.pageInfo.prevPageUrl : '' }
button.btn.btn-outline-dark.ml-4(id="previous_btn")
i(class="bi bi-arrow-left-circle-fill") Précédent
div.col-6
span(id='nextLink') #{products.pageInfo.nextPageUrl ? products.pageInfo.nextPageUrl : '' }
a.btn.btn-outline-dark.float-right.mr-4(id="next_btn") Suivant
i(class="fa-solid fa-circle-arrow-right")
window.addEventListener('DOMContentLoaded', () => {
console.log('dom content loaded')
document.getElementById('next_btn').onclick = function (e) {
console.log('next button clicked')
const nextLink = document.getElementById('nextLink').innerHTML;
fetch(nextLink).then(response => {
console.log(response);
}).catch(error => {
console.log(error)
})
console.log(nextLink)
}
});
You're doing it wrong. If you want to display Shopify products in your own App, you use the StorefrontAPI calls. With a StorefrontAPI token, you get products, and can display them. Trying to use Admin API calls is never going to work properly. Switch to StorefrontAPI and all your problems go away.

logout function refreshes the page but it's still logged in

I am following a course on Udemy, the instructor's side is using Angular 2 and I am trying to build the app using the latest version. The main problem I have, is that the logout function is accessed but because I have to refresh the page to display the login form again, for some reason, after the refresh, I see the login form but then it goes back to the part where I'm logged in.
Logout method on the back-end side:
#RequestMapping(value="/loggedOut", method=RequestMethod.POST)
public ResponseEntity logout(){
SecurityContextHolder.clearContext();
return new ResponseEntity("Logout Successfully!", HttpStatus.OK);
}
Logout function from my login service:
logOut() {
const url = 'http://localhost:8181/loggedOut';
const basicHeader = 'Basic ' + localStorage.getItem('credentials');
const headers = new HttpHeaders({
'x-auth-token' : JSON.stringify(localStorage.getItem('xAuthToken')),
'Authorization' : basicHeader
});
return this.http.post(url, '', { headers, responseType: 'text'});
The button responsible for logging out:
logout() {
this.loginService.logOut().subscribe(
res => {
location.reload();
console.log("Logged out")
},
error => {
console.log(error)
}
);
Technically, it goes as follow: Logged in -> Login form -> Logged in
Logged in:
Log in form:
If I remove the reload method, I can see that the logout method is accessed and I get a 200 from the back-end.
Network tab before refreshing:
The server response before refreshing:
Try clearing out your localStorage when logging out:
localStorage.clear();
Basically, this removes any trace that the app left when logging in.
**Try This Approach **
logout() {
this.loginService.logOut().subscribe(
res => {
if(res) {
// clear localStorage
localStorage.clear();
//navigate to login component
this.router.navigate(['loginPagePathName']);
console.log("Logged out")
}
},
error => console.log(error));
}
We don't need to refresh the page
Note :- You can also clear the local storage whenever login component load into the browser simply put localStorage.clear() inside ngOnInit method of loginComponent

How to get myshopify custom page content from server

I have created the my custom page called "pages.api.main-menu.liquid"
When I access page from preview mode it shows the the content.
The case is I want to take the content of this page from Next Server. So I sent a request directly to this page.
export default (req, res) => {
const {
SHOPIFY_STORE_URL,
SHOPIFY_ADMIN_API_KEY,
SHOPIFY_ADMIN_API_PASSWORD
} = process.env
serverCoreAPI
.get(
`https://${SHOPIFY_ADMIN_API_KEY}:${SHOPIFY_ADMIN_API_PASSWORD}#${SHOPIFY_STORE_URL}/pages/main-menu-api`
)
.then((response) => {
console.log(response)
res.status(200).send(response.data || { data: null })
})
.catch((e) => {
console.log(e)
})
}
I am taking as a response the error code 400.
Anyone can help with this?

Multiple axios calls after login that needs to wait each other, before redirecting user to dashboard on Vue.js [Timing issue]

Login.vue
methods: {
loginUser() {
this.$store.dispatch("auth/loginUser", { email: this.email, password: this.password })
.then(() => {
// Login ok, redirect user to dashboard
})
.catch(() => {
// Show error
})
}
}
Auth.js
actions: {
async loginUser ({dispatch}, {email, password}) {
return axios.post(url, {email, password})
.then(response => {
dispatch('otherAction');
})
.catch(response => {
})
},
async otherAction ({ dispatch, commit }) {
// Do other stuff
}
}
I use Vuex and actions to perform API calls. I need to wait otherAction dispatch before redirecting user to dashboard.
The problem is I can not use await in the then call. axios.post in the auth.js basically checks credentials of the user. After that I need to do a few more call to get all necessary data to show. Currently, user is redirected to dashboard, but I see errors on the dashboard because it doesn't wait until the 'get extra data of a user' call is completed to get the needed data. The thing is timing issue.
My way of thinking may be completely wrong. How can I make it work?
Make another action that dispatches all the other actions and stores the returned promises in an array then use Promise.all()

Categories

Resources