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

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));
}

Related

Adding Cookie to Request Header of a Fetch API

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));
}

fetch method JavaScript

I am working on a website and I am trying to write a script which sends data once someone creates an account. But I get some errors(attached a screenshot) and can't find a way to fix them as I'm still an intern. Hopefully someone can help me.
Thank you.
if (val2 == 1) {
fetch(hookURL, {
method: 'GET',
headers: {
'Content-Type': 'application/json',
},
body: attrString,
mode: 'no-cors'
})
.then((response) => {
//console.log('hook returned, response= ', response);
});
enter image description here
If You want to send data - use a different method ;)
Try POST instead of GET
Look at the below example from:
https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch
const data = { username: 'example' };
fetch('https://example.com/profile', {
method: 'POST', // or 'PUT'
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(data),
})
.then(response => response.json())
.then(data => {
console.log('Success:', data);
})
.catch((error) => {
console.error('Error:', error);
});

Error in calling POST api in react native by handling action in redux

i am fetching some data by using POST api call in which i have data and a token value for header, but i am getting bad response and i checked many docs but can't figure out the error, here is the code:
export const shareUserProfileHandler = (sharedReceiverData) => {
return dispatch => {
let formData = new FormData();
for (let key in sharedReceiverData) {
formData.append(key, sharedReceiverData[key]);
}
let requestConfig = {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'multipart/form-data',
'Authorization': 'Token 97a74c03004e7d6b0658b14ddb'
},
body: formData
};
fetch(`http://api.com`, requestConfig)
.then(response => response.json())
.then(response => {
alert('share user card api worked')
})
.catch(error => {
alert('api error ' + error)
})
}
};
the above is catching error and showing - SyntaxError: JSON Parse error: Unrecognized token'<'
Your response doesn't seem to be a JSON.
Replace
.then((response) => response.json())
For
.then((response) => { console.log('response', response); response.json() })
And check what is wrong with the response before the error.

Call REST API with auth token with React.js

This is a try of call a REST API that as an authentication token with React.js. I'm sending the token request as POST and it's been read as GET, can someone help me please?
componentDidMount() {
fetch("theURL/api-token-auth/", {
method: "POST",
headers: {
Accept: "application/json",
"Content-Type": "application/json",
email: "EMAIL",
password: "PASSWORD"
}
})
.then(res => {
if (res.ok) {
return res.json();
} else {
throw Error(res.statusText);
}
})
.then(json => {
this.setState({
isLoaded: true,
token: json
});
})
.catch(error => console.error(error));
}
You are correctly using the method POST, so that's not an issue. However, the data you want to send should be in the body instead of in the headers.
componentDidMount() {
const email = "test#example.com";
const password = "foobar";
fetch("theURL/api-token-auth/", {
method: "POST",
headers: {
Accept: "application/json",
"Content-Type": "application/json"
},
body: JSON.stringify({
email,
password
})
})
.then(res => {
if (res.ok) {
return res.json();
} else {
throw Error(res.statusText);
}
})
.then(json => {
this.setState({
isLoaded: true,
token: json
});
})
.catch(error => console.error(error));
}

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()

Categories

Resources