Store token generated on fetch() with React.js - javascript

From this code I get a token, I need to store the token to use in another fetch so I can refresh the token, what's the best way to do it?
I can only access the variable inside the function .then...
I would prefer to store the token in a encoded cookie, but I don't how to handle cookies em react, or how to encode or decode them.
componentDidMount() {
fetch("theURL/api-token-auth/", {
method: "POST",
headers: {
Accept: "application/json",
"Content-Type": "application/json"
},
body: JSON.stringify({
email: "EMAIL",
password: "PASS"
})
})
.then(res => {
if (res.ok) {
return res.json();
} else {
throw Error(res.statusText);
}
})
.then(json => {
this.setState({
isLoaded: true,
token: json
});
let token = this.state.token;
console.log("var token: ", token);
})
.catch(error => console.error(error));
}

Take a look on localStorage, is a good place for store tokens.
localStorage.setItem('token', 'userToken');
And then to recover the value just do:
const token = localStorage.getItem('token');
Take a deeper look here:Web Storage

Related

how can i send token to backend i n vue js

i'm trying to make payment to my backend, but each time i send the payment i get this message from my backend
{
"success": false,
"message": "No token Provided"
}
my backend requires authentication
this is my script tag
methods: {
sendTokenToServer(charge, response) {
const token = localStorage.getItem("token");
axios
.post(`http://localhost:5000/api/pay`, {
headers: {
Authorization: "Bearer" + token,
"x-access-token": token
},
totalPrice: this.getCartTotalPriceWithShipping,
})
.then(res => {
console.log(res);
});
}
}
};
</script>
when i check my dev tool i see my token
token: "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ"
this is my backend headers
let token = req.headers["x-access-token"] || req.headers["authorization"];
please how can i go about this
your code looks fine, just create an object then add it to the url i guess your looking for something like this.. try this
methods: {
sendTokenToServer(charge, response) {
var request = {
totalPrice: this.getCartTotalPriceWithShipping,
};
const token = localStorage.getItem("token");
axios
.post(`http://localhost:5000/api/pay`,request, {
headers: {
Authorization: "Bearer" + token,
"x-access-token": token
},
})
.then(res => {
console.log(res);
});
}
}
First parameter is your url,
Second parameter is your data,
Third parameters is your config.
You can make a post request like below
axios
.post(
`http://localhost:5000/api/pay`,
data,
{
headers: {
"Authorization": `Bearer ${token}` //mind the space before your token
"Content-Type": "application/json",
"x-access-token": token,
}
}
);
NOTE: data is your request body.
e.x.
{
"firstname": "Firat",
"lastname": "Keler"
}

cannot get XSRF-TOKEN from cookie in nextjs (Reactjs)

I create a login form using Nextjs and backend with Laravel 8, I generate an XSRF-TOKEN in Laravel then set it on cookie, I can see the token inside inspect element> application tab> cookie section, but I can't set it on my fetch request to make my login, I using redux to store my data such: products, auth, cart and etc
AuthAction.js code:
export const LOGIN_AUTH = "LOGIN_AUTH";
export const LOGOUT_AUTH = "LOGOUT_AUTH";
export const HandleLogin = (data) => {
return async (dispatch, getState) => {
const getCsrf = await fetch("http://localhost:8000/sanctum/csrf-cookie");
if (!getCsrf.ok) {
throw new Error("Faild to set csrf token");
}
console.log("getCsrf", cookie.load("XSRF-TOKEN"));
const response = await fetch("http://localhost:8000/api/app/user/login", {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify(data),
});
if (!response.ok) {
throw Error("Login faild");
}
try {
const responseData = await response.json();
console.log("login", responseData);
dispatch({
type: LOGIN_AUTH,
user: responseData,
});
} catch (err) {
console.log("Login err", err);
throw err;
}
};
};
after console.log("getCsrf", cookie.load("XSRF-TOKEN")); nothing happened.
what do I do wrong in my code?
cookie screenshot:
request response:
Use axios instead of fetch.
Example:
axios
.get("http://localhost:8000/sanctum/csrf-cookie", {
withCredentials: true,
})
.then((response) => {
axios("http://localhost:8000/api/app/user/login", {
method: "post",
data: data,
withCredentials: true,
})
.then((response) => {
console.log("login", response.data);
})
.catch((error) => {
console.log(error);
});
})
.catch((error) => {
// handle error
console.log(error);
})
.then(() => {
//
});
Since your next.js and laravel apps are on different origins, you need to set fetch to explicitly send cookies.
const response = await fetch("http://localhost:8000/api/app/user/login", {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify(data),
credentials: 'include'
});
You can read more about the credentials property in the MDN docs
Also, you can read the cookie in the front-end if it's http-only cookie.
Also, don't forget to set up Cross origin resource sharing in your backend app.

How to get 'public_Profile' of the user from the Facebook access_token using OAuth2

I wanted to use facebook login in the app. I successfully get Facebook Accesstoken and even the user info {id:'###', name:'###'}. But I wanted the users Email and other public_Profile info to register his email and other details. How can I do that. Following is my code..Did my scope values are wrong? how can I get public_profile info, particularly email to register it in my app.
const getFbToken = async (code) => {
const tokenUrl = "https://graph.facebook.com/v12.0/oauth/access_token";
const queryValues = {
code,
client_id: FB_APP_ID,
client_secret: FB_SECRET,
redirect_uri: redirect_uri, // address must match with google redirect uri
scope:"user_about_me,read_stream,publish_actions,user_birthday,offline_access,email",
};
const token = await axios
.get(tokenUrl, {
headers: {
"Content-Type": "application/json",
},
params:queryValues
})
.then((res) => {
console.log('response', res.data)
return res.data
}
) // returns {{access_token, refresh_token, Authorization Bearer and id_token}}
.catch((error) => {
console.error(`Failed to fetch auth tokens`, error.response.data);
});
console.log(token);
return token;
};
const getFbUser = async (access_token, token_type) => {
const fbUser = await axios
.get(
`https://graph.facebook.com/me`,
{
headers: {
Authorization: `Bearer ${access_token}`,
"Content-Type": "application/json",
},
}
)
.then((res) => res.data)
.catch((error) => {
console.error(`Failed to fetch user`);
throw new Error(error.message);
});
console.log('fbUser',fbUser)
return fbUser;

How to post query parameters with Axios?

I am trying to post on an API with some query params.
This is working on PostMan / Insomnia when I am trying to by passing mail and firstname as query parameters :
http://localhost:8000/api/mails/users/sendVerificationMail?mail=lol%40lol.com&firstname=myFirstName
However, when I am trying to do it with my react native app, I got a 400 error (Invalid Query Parameters).
This is the post method :
.post(`/mails/users/sendVerificationMail`, {
mail,
firstname
})
.then(response => response.status)
.catch(err => console.warn(err));
(my mail and firstname are console.logged as follow: lol#lol.com and myFirstName).
So I don't know how to pass Query Parameters with Axios in my request (because right now, it's passing data: { mail: "lol#lol.com", firstname: "myFirstName" }.
axios signature for post is axios.post(url[, data[, config]]). So you want to send params object within the third argument:
.post(`/mails/users/sendVerificationMail`, null, { params: {
mail,
firstname
}})
.then(response => response.status)
.catch(err => console.warn(err));
This will POST an empty body with the two query params:
POST
http://localhost:8000/api/mails/users/sendVerificationMail?mail=lol%40lol.com&firstname=myFirstName
As of 2021 insted of null i had to add {} in order to make it work!
axios.post(
url,
{},
{
params: {
key,
checksum
}
}
)
.then(response => {
return success(response);
})
.catch(error => {
return fail(error);
});
In my case, the API responded with a CORS error. I instead formatted the query parameters into query string. It successfully posted data and also avoided the CORS issue.
var data = {};
const params = new URLSearchParams({
contact: this.ContactPerson,
phoneNumber: this.PhoneNumber,
email: this.Email
}).toString();
const url =
"https://test.com/api/UpdateProfile?" +
params;
axios
.post(url, data, {
headers: {
aaid: this.ID,
token: this.Token
}
})
.then(res => {
this.Info = JSON.parse(res.data);
})
.catch(err => {
console.log(err);
});
You can use params and body together in a request with axios
sendAllData (data) {
return axios
.post(API_URL + "receiveData", JSON.stringify(data), {
headers: { "Content-Type": "application/json; charset=UTF-8" },
params: { mail: xyx#example.col }, //Add mail as a param
})
.then((response) => console.log("repsonse", response.status));
}

React JS how to pass values between pages using session storage

I have a react JS login page that accepts the user name and password. Upon entering the user name and and password, the credentials are processed against a json (API) file, which generates a token for the client. My goal is to pass the token to a landing page after the client has logged in and populate a dropdown list with the clients respective data. The problem I am facing is getting the clients token to pass from my login page to the landing page.
In my login page, I am using Fetch to retrieve the token from the API and then store the token using session-storage. The code snippet for getting the token:
componentDidMount() {
this.fetchData();
}
//request the token
fetchData() {
return fetch('http://myapiaut:1111/api/auth', {
method: 'POST',
headers: {
'Content-type': 'application/json',
},
body: JSON.stringify({
username: 'myAdminusername',
password: 'myAdminPassword',
Authorization: 'myAdminPassword',
})
}) /*end fetch */
.then(results => results.json())
.then(data => {
this.setState({ data: data })
sessionStorage.setItem("token", data)
})
}
//authenticate request
requestUserInfo() {
var token = sessionStorage.getItem("token");
return fetch('http://myapiaut:1111/api/auth', {
method: 'GET',
headers: new Headers({
Authorization: 'Bearer' + sessionStorage.token
}),
})
.then((response) => response.json());
}
Landing page
componentDidMount() {
fetch('http://myapiclients:22222/api/clients', {
method: 'GET',
headers: {
'Content-type': 'application/json',
'Authorization': 'Bearer ' + sessionStorage.token
},
})
.then(results => results.json())
.then(data => this.setState({ data: data }))
}
...going back to the login page, I confirmed that I'm getting the token via fetchData function, but the problem I am encountering is properly storing the token so that it may be passed to the landing page.
FYI- I've already built the landing page and it functions properly when I manually copy the generated token into the Authorization section of the Fetch.
...Could, I please get some help as to what I'm doing wrong?
The problem is here:
.then(data => this.setState({ data: data }))
.then(data => sessionStorage.setItem('token', data))
setState doesn't resolve a Promise so it does not have then()
Change it to something like:
.then(data => {
this.setState({ data: data })
sessionStorage.setItem('token', data)
})
In landing page:
componentDidMount() {
fetch('http://myapiclients/api/clients', {
method: 'GET',
headers: {
'Content-type': 'application/json',
'Authorization': 'Bearer ${token}' // token is not defined!
},
})
.then(results => results.json())
.then(data => this.setState({ data: data }))
}
token is not defined, so it will be 'Bearer undefined', either define it before fetch(...) with sessionStorage.getItem("token") or in fetch headers do something like:
'Authorization': 'Bearer ' + sessionStorage.token

Categories