Github Rest API not fetching results on hosting - reactjs

I am supposed to use GITHUB REST API to fetch details such as username and repositories of a user. I am getting the results on localhost and when I deploy this project using VERCEL the project is hosted fine. The problem is that in the hosted URL the I am not able to see the results that were supposed to be fetched by the API. This is the error in the console:
GEThttps://api.github.com/users/Xaid-vfx/repos?page=1&per_page=8 [HTTP/2 401 Unauthorized 581ms]
Uncaught (in promise) HttpError: Bad credentials
What I understood is that my Authorisation key is not working whenever I am trying to deploy using vercel.
Here's the code that I am using to make API calls
const octokit = new Octokit({
auth: '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'
});
useEffect(() => {
async function get() {
setloading(true);
const req1 = await octokit.request('GET /users/{username}/repos?page=1&per_page=1000', {
username: username
})
setsize(req1.data.length)
console.log(req1.data.size);
const details = await octokit.request('GET /users/{username}', {
username: username
})
// console.log(details);
setloading(false)
return [details.data]
}
if (username != '') {
get().then(function (res) {
// setrep(res[0]);
console.log(res[0]);
setname(res[0].login);
seturl(res[0].avatar_url);
setbio(res[0].bio);
setlink(res[0].html_url)
})
}
}, [count])
This code is working fine on localhost and giving the results . When I deploy using vercel from GitHub, it does not fetch results on localhost as well as the deployed url. This has something to do with authorisation token

Related

req.user is undefined in passportjs even when credentials is included

I'm trying to send user information from front end after being google authenticated to the backend. However, even when I included credentials, the user information is not being sent to the backend which is strange. I'm thinking this might be a same site issue but I'm not totally sure and am not even sure of how to go about fixing that problem. If somebody can help me I would appreciate it.
This is the request being sent from the frontend:
export const checkLogin = createAsyncThunk(
"user/checkLogin",
// function has empty argument parameter
async () => {
const url = "http://localhost:3001/auth/profile";
const user = await fetch(url, {
credentials: "include",
}).then((response) => response.json());
return user;
}
);
This is the code in the backend for google authentication. But the problem is that in the /profile route we are not getting any information related to the user. It is only "undefined" which I'm not sure why.
authRouter.get("/profile", (req, res) => {
console.log(req.user);
if (req.user) {
res.send({
redirectLink: "http://127.0.0.1:5173",
user: req.user,
});
} else {
res.send({
redirectLink: "http://127.0.0.1:5173",
user: null,
});
}
});
authRouter.get(
"/google",
passport.authenticate("google", {
scope: ["profile"],
})
); // passport knows to authenticate with google
authRouter.get(
"/google/redirect",
passport.authenticate("google"),
(req, res) => {
// in this step google send back the info with a code that can then be used
// by the application to pull data from the user on google
console.log(req.user);
res.redirect("http://127.0.0.1:5173"); // go back to the home page
}
);
Nevermind! I got it. I solved this by changing the Vite configuration for the hosting. Instead of hosting it using 127.0.0.1, I changed it to verbatim, which is then localhost. I guess this is like same-site cookie problem.
If anyone runs into this problem you can change this in the vite.config file. The link to do this is here:
https://vitejs.dev/config/server-options.html#server-host

React App, Express Server - Set cookie not being stored in browser

The long short is...
My express backend sets a cookie and sends it back to the client, everything works great when I use Postman and my React Native app. The issue is the web version which is done via ReactJs makes the same request but cookie is stored in the browser.
So I know cookies are working but not for the web version which is strange when I created a test endpoint http://localhost:3000/server and call it straight from the browser the cookie is stored.
So this is my code doing a simple fetch to the server which then sends back a cookie:
const fetchData = async () => {
try {
const res = await fetch(`http://192.168.0.11:3000/server/`, {
credentials: "include",
});
if (res.ok) {
const resData = await res.json();
console.log({ resData });
}
} catch (err) {
console.log({ err });
}
};
The request came back successful but no cookie is stored
Access the same endpoint from the browser directly results in this:
An extract from the response header while being sent shows that the cookie was sent in the response just not stored in the frontend
Was a pretty simple fix
I was using http://localhost:3001 for the react app I just simply used the ip address instead http://192.168.0.11:3001

Making a delete request using Axios to Laravel API throws an error but works fine in insomnia

Hi I am creating a web app using create-react-app which consumes endpoints developed in laravel 5.
When I make a Delete request using axios to the server, I get this error Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://127.0.0.1:8000/api/carts/7?api_token={api_token}. (Reason: Did not find method in CORS header ‘Access-Control-Allow-Methods’) Whereas, when I send the same request on Insomnia (HTTP Rest Client), I donot get any error.
Here is the react code
handleDelete = ( cartId ) => {
const api_token = localStorage.getItem('jbs_user_api_token');
console.log("Delete cart item: ", cartId);
axios.delete(`carts/${cartId}?api_token=${api_token}`)
.then( res => {
console.log(res);
})
.catch( err => {
console.log(err);
});
}
Following is the endpoint in Laravel 5, the react app is making the aforementioned request to
Route::resource('carts', 'API\CartAPIController');
Here is the method (laravel) that handles the delete request
public function destroy($id)
{
$cart = $this->cartRepository->findWithoutFail($id);
if (empty($cart)) {
return $this->sendError('Cart not found');
}
$cart = $this->cartRepository->delete($id);
return $this->sendResponse($cart, __('lang.deleted_successfully', ['operator' => __('lang.cart')]));
}
Definitely, there is no error on the API (Backend) since the request works fine in insomnia. Plus both the applications (react and laravel) are served from localhost.
Please help
In your package.json file of frontend/client folder try to add proxy like this
"name": "app_name",
"proxy": "http://127.0.0.1:8000"
The issue is resolved by adding Laravel Cors package in the laravel App (API Provider).
Following is the link to Laravel Cors pakage
https://github.com/fruitcake/laravel-cors

Not able to connect by frontend to backend on heroku after successful deployment

I have deployed my mern stack app on heroku. The problem is i am not able to make any request to my backend .
I am connecting my frontend to my backend like this...
API=http://localhost:5000/api
import { API } from "../../backend";
import { signin } from "../../auth/helper";
export const getAllProducts = () => {
return fetch(`**${API}/allProducts**`, { method: "GET" })
.then((response) => {
return response.json();
})
.catch((err) => {
console.log(err);
});
};
I think i am caliing api on my local host thatswhy i am not getting connected to backend.
What should i do here?
If you want anything else you can tell me .
In client side (frontend) code, localhost is the end user's machine because the code runs in the browser of that machine. Therefore, when it's trying to fetch at localhost:5000/api, it's looking for a Node.js server on the end user's machine, not your actual production server on Heroku.
Instead of localhost, use the domain Heroku assigned to your app. You can find it in the Settings of your dyno and should look something like this https://yourapp.herokuapp.com/. Additionally, you can use NODE_ENV env var to set the API string so it works both on development and production:
const API = process.env.NODE_ENV === 'production' ? 'https://yourapp.herokuapp.com/api' : 'http://localhost:5000/api';

AngularFire2 - using access token from Google Auth for Google APIs

Google Authentication through AngularFire2 returns the Firebase access token, but not the Google access token for use on Google APIs. What's the proper way to get the access token from the AngularFire2 auth?
Angular: 2.4.9
Firebase: 3.5.2
AngularFire: 2.0.0-beta.8
Here's a plunkr:
http://plnkr.co/edit/qIbtcp?p=preview
You'll notice in the constructor:
constructor(af: AngularFire, public auth$: AngularFireAuth, public http:Http) {
auth$.subscribe((state: FirebaseAuthState) => {
if(state){
this.signedIn = true
}
});
firebase.auth()
.getRedirectResult()
.then((result) => {
console.log('result', result);
if (result.credential) {
// This gives you a Google Access Token.
var token = result.credential.accessToken;
console.log('token',token)
this.getPeople(token)
.subscribe(
people => console.log('people',people),
error => console.log(error));
}
var user = result.user;
})
.catch(err => console.log(err));
}
Where I call firebase.auth() is where I try to get the Google Access Token. However on first login, I get this error:
{
error: {
code: 403,
message: "Request had insufficient authentication scopes.",
status: "PERMISSION_DENIED"
}
}
I know this shouldn't happen because I tried the same setup with strictly Firebase (no AngularFire2), in this example:
https://embed.plnkr.co/zxOfRZ1PDDb7ee5qzIKW/
So is there an issue with sharing auth tokens between AngularFire and just Firebase? Does anyone have an example of this working?
Found a similar issue on StackOverflow:
Using Firebase Auth to access the Google Calendar API
I ended up using the same approach, it seems that you need to manually use the Google API's Javascript client, and use that credential to sign in with Firebase.

Resources