Adding Cookie to Request Header of a Fetch API - javascript

The issue I have is Cookie is not added to the request header therefore I receive a 403 status. To explain further I am implementing a system link where when a user opens a page, a request token is is fetched and added to the META of the html and also saved in the document.cookie. When the user decides to login, the fetch request below fetchSignIn should automatically add a cookie because I am setting credentials: "include" but it doesn't. I have looked at other examples but I don't understand where my implementation is wrong.
Login implementation using OOP
class Login {
// Private methods...
fetchSignIn (obj, url) {
console.log("Cookie ", document.cookie);
fetch(url, {
method: "POST",
mode: "cors",
credentials: "include",
body: JSON.stringify(obj),
headers: {
"Content-Type": "application/json",
"Authorization": "",
"X-XSRF-TOKEN": getQSelector('meta[name="_csrf"]').content
}
})
.then((response) => response.text())
.then((data) => {
console.log(data);
})
.catch((error) => {
console.error('Error: ', error.message);
});
}
}
Fetch token on opening of the page
window.addEventListener("DOMContentLoaded", (e) => {
_loadCSRF(CSRFDOMLOAD);
})
const _loadCSRF = (path) => {
fetch(path) // GET Request
.then((response) => response.json())
.then((data) => {
console.log(data);
document.cookie = data.headerName + "=" + data.token;
getQSelector('meta[name="_csrf_header"]').setAttribute("content", data.headerName);
getQSelector('meta[name="_csrf"]').setAttribute("content", data.token);
})
.catch((err) => console.error("Failed csrf fetch ", err));
}

Related

Fetch requests for token not passed to next fetch request, 401 returned

I'm reaching out to an endpoint with fetch to get a bearer token that will then be used in another fetch request for authentication. I've used Postman first and verified that the endpoints I'm accessing are working, however with my fetch requests below I get a 401.
I have checked in the console that the Authorization is updated after the first fetch and it's passed to the second however I continue to get a 401.
The first call reaches to ./auth and a bearer token is returned. That token is passed off to the next fetch request and but I am getting a 401.
What am I missing or doing wrong, a second pair of eyes could help.
const token = "./auth";
const listings = "./listings";
let clientHeaders = new Headers();
let raw = JSON.stringify({
email: "fake#account.com",
password: "12345",
});
clientHeaders.append("Authorization", "");
clientHeaders.append("Content-Type", "application/json");
clientHeaders.append("Cookie", "");
let req = {
method: "POST",
headers: clientHeaders,
body: raw,
redirect: "follow",
};
fetch(token, req)
.then((response) => response.json())
.then((result) => {
return fetch(listings, {
method: "GET",
headers: {
Authorization: result.token,
"Content-Type": "application/json",
},
});
})
.then((response) => {
return response.json();
})
.then((data) => {
console.log(JSON.parse(data));
})
.catch((error) => {
console.log("error: ", error);
});
You likely need to include the literal word "Bearer" and a space preceding the token in the header:
{
Authorization: `Bearer ${result.token}`
}
// or
{
Authorization: "Bearer " + result.token
}

how to use headers in fetch on React-Native or Expo

I want to communicate with the server.
In order to communicate with the server, two items must be added to headers.
Note: The key value written is not the actual key value.
api_key: "abcdegeg123456842536ebebeb1yeyju",
game_key: "abcdegeg123456842536ebebeb1yeyju"
The code I tried to communicate with:
checkNickName = async () => {
fetch("http://192.168.0.44:11000/v1/point/auth/change_nickname", {
method: "POST",
body: JSON.stringify({
wallet_address: "0f8751828af26816ef996c37e611b945304a6e99",
new_nickname: this.state.nickname
}),
headers: {
// "Content-Type": "application/json"
api_key: "abcdegeg123456842536ebebeb1yeyju",
game_key: "abcdegeg123456842536ebebeb1yeyju"
}
})
.then(res => res.json())
.then(response => {
console.log("response:" + response);
console.log(response.resultCode);
if (response.resultCode == "S000") {
Alert.alert("info","scess");
} else alert(response.result);
})
//console.log("Success:", JSON.stringify(response))
.catch(error => console.error("Error:", error));
};
But this is not working
Error:, [TypeError: Network request failed]
How can I communicate with the server? Is there another way?
thank you in advance
It was a mistake in my address,
but the server receiving the data says the data is null. How can we solve the problem?
I solved it by using formdata.
usePage.js
async checkNickName() {
let formdata = new FormData();
formdata.append(
"wallet_address",
"gBx0f8751828af26816ef996c37e611b945304a6e99"
);
formdata.append("new_nickname", this.state.nickname);
fetch("http://192.168.0.26:11000/v1/point/auth/change_nickname", {
method: "POST",
body: formdata,
headers: {
"Content-Type": "multipart/form-data",
api_key: "5b95576338b1eb1c53a1ae3f904dc7c5",
game_key: "bf61b73dd871c2973188706d813002c2"
}
})
.then(res => res.json())
.then(response => {
console.log(response);
console.log(response.resultCode);
if (response.resultCode == "S002") {
AsyncStorage.setItem("gbrickobj", this.state.gbrickobj);
AsyncStorage.setItem("nickname", this.state.nickname);
this.props.navigation.navigate("RegisterSecurity");
} else if (response.resultCode == "S001") {
this.setState({
checknick: "this nickname already use nickname."
});
} else {
Alert.alert("info", "check address.");
}
})
.catch(error => console.error("Error:", error));
}

Axios get request response with 403 error forbidden

I'm new in react . Trying to make "get" request and getting 403 error forbidden, "Response for preflight does not have HTTP ok status.". In network tab in Request Method instead of "get" method shows "options". What could be the problem? Cors already open , problem with token
let token = localStorage.getItem("token")
axios
.get("http://dev.*****************get-template", {
headers: {
Authorization: `Bearer + ${token}`,
},
})
.then(res => {
console.log("Success")
})
.catch(error => {
console.log(error)
})
that's how I'm saving token. May be I'm not correctly saving it in localStorage? But when console.log it displays fine
event.preventDefault()
const formdata = new FormData()
formdata.append("username", this.state.userLogin.email)
formdata.append("password", this.state.userLogin.password)
axios
.post("http://dev.****************/get-token", formdata)
.then(res => {
if (res.data) {
console.log(res.data)
localStorage.setItem("token", res.data.access_token)
localStorage.setItem("updToken", res.data.update_token)
this.props.history.push("/settings")
}
})
.catch(error => {
console.log(error)
})
I see a problem in your Bearer token
you write it:
Authorization: `Bearer + ${token}`
but it should be :
Authorization: `Bearer ${token}`,
and the full answer is :
let token = localStorage.getItem("token")
axios
.get("http://dev.*****************get-template", {
headers: {
Authorization: `Bearer ${token}`, //here remove + in template litereal
},
})
.then(res => {
console.log("Success")
})
.catch(error => {
console.log(error)
})
Do it like this:
let token = localStorage.getItem("token")
axios.defaults.headers.common['Authorization'] = token
axios
.get("http://dev.*****************get-template")
.then(res => {
console.log("Success")
})
.catch(error => {
console.log(error)
})
This is due to CORS issue.
To solve this you need to set Access-Control-Allow-Origin header on your server side, allowing the domain from which you are sending the request or you can set it to *

Api call using fetch with method get

I have to set an header in api call. My POST API calls are working fine. But in my get api calls, header is not getting set.
return fetch('http://api-call.com', {
method: 'GET',
headers: {
Accept: 'application/json',
'Content-Type': 'application/json',
'custom-security':'XXXX',
'Purchase-Code':'XXXXXXX',
'Content-Type':'application/json',
'Cache-Control':'max-age=640000'
}
})
.then((response) => response.json())
.then((responseJson) => {
console.log(responseJson);
})
.catch((error) => {
console.error(error);
});
You should setup a Request object and pass your headers wrapped into a Headers object, like:
var request = new Request('http://api-call.com', {
method: 'GET',
headers: new Headers({
'Accept': 'application/json',
'custom-security':'XXXX',
'Purchase-Code':'XXXXXXX',
'Content-Type':'application/json',
'Cache-Control':'max-age=640000'
})
});
Then just invoke fetch with your request as parameter:
fetch(request)
.then((response) => response.json())
.then((responseJson) => {
console.log(responseJson);
})
.catch((error) => {
console.error(error);
});
Check reference
2021 answer: just in case you land here looking for how to make GET and POST Fetch api requests using async/await or promises as compared to axios.
I'm using jsonplaceholder fake API to demonstrate:
Fetch api GET request using async/await:
const asyncGetCall = async () => {
try {
const response = await fetch('https://jsonplaceholder.typicode.com/posts');
const data = await response.json();
// enter you logic when the fetch is successful
console.log(data);
} catch(error) {
// enter your logic for when there is an error (ex. error toast)
console.log(error)
}
}
asyncGetCall()
Fetch api POST request using async/await:
const asyncPostCall = async () => {
try {
const response = await fetch('https://jsonplaceholder.typicode.com/posts', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
// your expected POST request payload goes here
title: "My post title",
body: "My post content."
})
});
const data = await response.json();
// enter you logic when the fetch is successful
console.log(data);
} catch(error) {
// enter your logic for when there is an error (ex. error toast)
console.log(error)
}
}
asyncPostCall()
GET request using Promises:
fetch('https://jsonplaceholder.typicode.com/posts')
.then(res => res.json())
.then(data => {
// enter you logic when the fetch is successful
console.log(data)
})
.catch(error => {
// enter your logic for when there is an error (ex. error toast)
console.log(error)
})
POST request using Promises:
fetch('https://jsonplaceholder.typicode.com/posts', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
// your expected POST request payload goes here
title: "My post title",
body: "My post content."
})
})
.then(res => res.json())
.then(data => {
// enter you logic when the fetch is successful
console.log(data)
})
.catch(error => {
// enter your logic for when there is an error (ex. error toast)
console.log(error)
})
GET request using Axios:
const axiosGetCall = async () => {
try {
const { data } = await axios.get('https://jsonplaceholder.typicode.com/posts')
// enter you logic when the fetch is successful
console.log(`data: `, data)
} catch (error) {
// enter your logic for when there is an error (ex. error toast)
console.log(`error: `, error)
}
}
axiosGetCall()
Authenticated POST request using Axios:
const axiosPostCall = async () => {
try {
const { data } = await axios.post('https://jsonplaceholder.typicode.com/posts', {
// your expected POST request payload goes here
title: "My post title",
body: "My post content."
},{
headers: {
Authorization:
`Bearer ${token}`
}
})
// enter you logic when the fetch is successful
console.log(`data: `, data)
} catch (error) {
// enter your logic for when there is an error (ex. error toast)
console.log(`error: `, error)
}
}
axiosPostCall()

axios preflight http status code 500

I can't seem to make the yelp API work for me. I get past the first ajax but the I get error on the second.
XMLHttpRequest cannot load https://api.yelp.com/v3/businesses/search. Response for preflight has invalid HTTP status code 500
I am running this on localhost:3000 and I'm using Allow-Control-Allow-Origin: * extension on Chrome.
This is my code on client side:
axios({
method: 'post',
url: 'https://api.yelp.com/oauth2/token',
data: 'grant_type=client_credentials'
+ '&client_id='+api[0]
+ '&client_secret='+api[1]
}).then(res => {
USER_TOKEN = res.data.access_token;
const AuthStr = 'Bearer '.concat(USER_TOKEN);
axios.get(api[2], { headers: { Authorization: AuthStr } })
.then(res => {
// If request is good...
console.log(response.data);
})
.catch((error) => {
console.log('error ' + error);
});
})
.catch((error) => {
console.log('error ' + error);
});

Categories

Resources