Closed startthecode closed 7 months ago
How to use nodejs api of google auth in axios fetch using API URL directly on anchor tag is not safe and fetching this using axios is not working as expected
I do not understand this question, perhaps these resources can be of assistance:
Hi @danielbankhead, Suppose I log in to Google and get redirected to a callback URL where I update my user information in the database using Node. How will my front end know whether the login was successful? Should I call an API to check whether the user was created successfully?
My approach
Many thanks Ashish
Suppose I log in to Google and get redirected to a callback URL where I update my user information in the database using Node. How will my front end know whether the login was successful?
That would depend on your authorization model - if redirecting the successful response from the backend confirms a successful login.
To make this easier I would recommend the Google Identity Services JavaScript library for the frontend:
Further reading:
How to use nodejs api of google auth in axios fetch using API URL directly on anchor tag is not safe and fetching this using axios is not working as expected
// react js fetch('http://localhost:5000/auth/google') .then(response => { // Handle response (e.g., redirect user to Google login page) }) .catch(error => { // Handle error });
Node js API export const authGoogle = asyncErrorHandler(async (req, res) => { // Redirect to Google's OAuth consent screen const url = googleAuthClient.generateAuthUrl({ access_type: "offline", scope: ["email", "profile"], redirect_uri: "http://localhost:5000/auth/google/callback", // Ensure this matches your actual callback URL }); res.redirect(url); });
export const googleCallback = asyncErrorHandler(async (req, res) => { const { code } = req.query; if (!code) { res.status(400).send("No authorization code"); return; }
try { const { tokens } = await googleAuthClient.getToken(code); // Set the credentials on the OAuth2 client. googleAuthClient.setCredentials(tokens);
} catch (error) { console.error("Error retrieving user info:", error); res.status(500).send("Error retrieving user info"); } });