Can't send any header - reactjs

I'm trying to access some data from my api using axios or fetch, but none of them is sending the headeri give them.
first the constructor of the react class
constructor(props) {
super(props);
this.state = {
loaded: false,
addresses: []
};
this.myHeaders = new Headers();
this.requestOptions = {};
this.token = `Bearer ${localStorage.getItem('token')}`
}
then the getAddresses function that should send a header with a token and get the addresses.
I'm showing you the 2 ways i used, but none of them worked.
first way
getAddresses() {
axios.default({
method: 'get',
url: "http://localhost:8090/address",
headers: {
'Authorization': `Bearer ${localStorage.getItem('token')}`
}
})
.then(response => {
this.setState({loaded:true, addresses:response.json()})
})
.catch(error => {
console.log('====================================');
console.log('error => ', error);
console.log('====================================');
})
}
second way
getAddressess () {
if (this.myHeaders.get("Authorization"))
this.myHeaders.set("Authorization", `Bearer ${localStorage.getItem('token')}`)
else
this.myHeaders.append("Authorization", `Bearer ${localStorage.getItem('token')}`)
if (this.myHeaders.get("Access-Control-Allow-Origin"))
this.myHeaders.set("Access-Control-Allow-Origin", `*`)
else
this.myHeaders.append("Access-Control-Allow-Origin", `*`)
if (this.myHeaders.get("Access-Control-Allow-Methods"))
this.myHeaders.set("Access-Control-Allow-Methods", 'GET')
else
this.myHeaders.append("Access-Control-Allow-Methods", `GET`)
this.requestOptions = {
method: 'GET',
headers: this.myHeaders
};
fetch("http://localhost:8090/address", this.requestOptions)
.then(response => {
this.setState({loaded:true, addresses:response.json()})
})
.catch(error => console.log('error', error))
console.log('====================================');
console.log(this.token);
console.log('====================================');
}

Related

React axios patch request giving 401 error but authorization is provided

I am trying to add a user to a group with a axios patch request. the data is all correct but i get a 401 error even though i include the Authorization in the header. Code is below any help is greatly appreciated.
handleJoin = (e, group) => {
e.preventDefault();
axios.get('http://localhost:8000/core/current_user/', {
headers: {
Authorization: `JWT ${localStorage.getItem('token')}`
}
})
.then((user) => {
let group_data = new FormData();
group_data.append('user', user.data.id);
group_data.append('group', group.id);
for (var value of group_data.values()) {
console.log(value);
}
axios.patch(`http://localhost:8000/core/usergroup/${user.data.id}/`, {
group_data,
headers: {
Authorization: `JWT ${localStorage.getItem('token')}`,
'Content-Type': 'application/json',
},
})
.then((res) => {
console.log(res.data);
})
.catch((err) => {
console.log(err);
});
})
.catch((err) => {
console.log(err);
});
}
Edit: Attempting to rewrite the request and changing the position of the group_data variable stops the 401 error but does not change the data in the model.
handleJoin = (e, group) => {
e.preventDefault();
axios.get('http://localhost:8000/core/current_user/', {
headers: {
Authorization: `JWT ${localStorage.getItem('token')}`
}
})
.then((user) => {
let group_data = new FormData();
group_data.append('user', user.data.id);
group_data.append('group', group.id);
for (var value of group_data.values()) {
console.log(value);
}
axios.patch(`http://localhost:8000/core/usergroup/${user.data.id}/`, group_data,{
headers: {
Authorization: `JWT ${localStorage.getItem('token')}`,
'Content-Type': 'application/json',
},
})
.then((res) => {
console.log(res.data);
})
.catch((err) => {
console.log(err);
});
})
.catch((err) => {
console.log(err);
});
}
Edit:
I changed the handler and now it is updating the group field but completely overwriting it. When i try to send group as a list it gives error expecting a int that represents pk. So my question is, is there a method to patch the model without overwriting the previous information.
Handler with group value as id
e.preventDefault();
axios.get('http://127.0.0.1:8000/core/current_user/', {
headers: {
Authorization: `JWT ${localStorage.getItem('token')}`
}
})
.then((user) => {
let group_data = new FormData();
group_data.append('user', user.data.id);
group_data.append('group', group.id);
for (var value of group_data.values()) {
console.log(value);
}
axios.patch(`http://127.0.0.1:8000/core/usergroup/${user.data.id}/`, group_data,{
headers: {
Authorization: `JWT ${localStorage.getItem('token')}`,
'Content-Type': 'application/json',
},
})
.then((res) => {
console.log(res.data);
})
.catch((err) => {
console.log(err);
});
})
.catch((err) => {
console.log(err);
});
}
Handler with group as list
handleJoin = (e, group) => {
e.preventDefault();
axios.get('http://127.0.0.1:8000/core/current_user/', {
headers: {
Authorization: `JWT ${localStorage.getItem('token')}`
}
})
.then((user) => {
axios.get(`http://127.0.0.1:8000/core/usergroup/${user.data.id}/`, {
headers: {
Authorization: `JWT ${localStorage.getItem('token')}`,
'Content-Type': 'application/json',
}
})
.then((usergroup) => {
let group_data = new FormData();
let prev = usergroup.data.group
prev.push(group.id);
console.log(prev);
group_data.append('user', user.data.id);
group_data.append('group', prev);
for (var value of group_data.values()) {
console.log(value);
}
axios.patch(`http://127.0.0.1:8000/core/usergroup/${user.data.id}/`, group_data,{
headers: {
Authorization: `JWT ${localStorage.getItem('token')}`,
'Content-Type': 'application/json',
},
})
.then((res) => {
console.log(res.data);
})
.catch((err) => {
console.log(err);
});
})
})
.catch((err) => {
console.log(err);
});
}
The backend is written with Django and i realize the problem may be there instead of the front end. I am also posting my serializer and views in case they may be the problem. Any help would be really appreciated.
Serializer
class UserGroupSerializer(serializers.ModelSerializer):
groups = GroupSerializer(many=True, read_only=True,)
class Meta:
model = UserGroup
fields = '__all__'
View
class UserGroupDetail(APIView):
def patch(self, request, pk):
usergroup = UserGroup.objects.get(pk=pk)
serializer = UserGroupSerializer(instance=usergroup, data=request.data, partial=True)
if serializer.is_valid():
serializer.save()
return Response(serializer.data, status=status.HTTP_201_CREATED)
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
Your authorization header should be
Authorization: `Bearer ${localStorage.getItem('token')}`

Cannot get componentDidMount() to update empty array via this.setState with fetched JSON data

I have an empty array declared as such:
class EditPlaylistDetails extends Component {
constructor(props) {
super(props);
this.state = {
allPlaylists: []
}
};
And my ComponentDidMount() is:
componentDidMount() {
fetch('http://localhost:5040/playlist/', {
method: 'GET',
headers: new Headers({
'Content-Type': 'application/json',
'Authorization': this.props.sessionToken
})
}).then((response) => response.json())
.then((res) => {
console.log(res);
}).then((res) => {
this.setState({
allPlaylists: res
},
() => console.log(this.state.allPlaylists));
})
};
Two problems:
#1) When I try to call upon this fetched data via a .map function, it comes back as "undefined".
#2) The '() => console.log(this.state.allPlaylists))' code snippet doesn't even fire off at all. It doesn't attempt to execute the console.log.
I am able to console.log(res) within that snippet of code and it displays the updated allPlaylists array with all of the info without issue.
Add return to the second promise handler
componentDidMount() {
fetch('http://localhost:5040/playlist/', {
method: 'GET',
headers: new Headers({
'Content-Type': 'application/json',
'Authorization': this.props.sessionToken
})
}).then((response) => response.json())
.then((res) => {
console.log(res);
return res;
}).then((res) => {
this.setState({
allPlaylists: res
},
() => console.log(this.state.allPlaylists));
})
};
For one of my projects, removing the { before this.setState( worked.
componentDidMount() {
fetch('http://localhost:5040/playlist/', {
method: 'GET',
headers: new Headers({
'Content-Type': 'application/json',
'Authorization': this.props.sessionToken
})
}).then((response) => response.json())
.then((res) => {console.log(res);})
.then((res) => this.setState({allPlaylists: res})};

React Native refreshing data

I'm trying to refresh some data when users re-vistis the screen. The way im using other places and it works. but can't figure out why this won't fly on this screen?
componentDidMount = () => {
this.props.navigation.addListener('didFocus', this.handleDidFocus)
}
async handleDidFocus() {
...
}
This is how I load data the first time and want to load it again when users revisits.
componentWillMount() {
this.getGroupAccepted();
}
async getGroupAccepted() {
if (this.state.token == null) {
var token = await AsyncStorage.getItem("token");
this.setState({ "token": token });
}
fetch('https://.../api/group/getActive', {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify({
token: this.state.token
})
})
.then(response => response.json())
.then((data) => {
this.setState({
groups_accepted: data.groups_active,
loading: false,
});
})
.catch((error) => {
console.error(error);
});
}
This is what worked. Now when a user revisits the screen it loads the data once again.
componentDidMount = () => {
this.props.navigation.addListener('didFocus', this._handleDataChange)
}
_handleDataChange = () => {
this.getGroupAccepted();
}

How to use post method in react native?

constructor(props) {
super(props);
this.state = {text: this.props.navigation.state.params.text,
name:this.props.navigation.state.params.name};
}
manage = () => {
Alert.alert('done')
Actions.reset('mainScreen');
fetch("http://ip/api/confirm", {
method: "POST",
headers: {
Accept: "application/json",
"Content-Type": "application/json"
},
body: JSON.stringify({
name: this.props.navigation.state.params.name,
text:this.props.navigation.state.params.text
})
})
.then(response => response.json())
.catch(error => {
console.error(error);
});
}
i want to do this
when i press in button go to manage function
and post the text and the name to my api i dont know how can i pass them
its give me this error :
network request failed
any help please
I recommend you to use axios to make network requests.
Installing:
npm i -S axios
Performing a POST request:
import axios from 'axios';
axios({
url: 'http://ip/api/confirm',
method: 'post',
data: {
name: this.props.navigation.state.params.name,
text: this.props.navigation.state.params.text,
},
headers: {
Accept: 'application/json',
'Content-Type': 'application/json',
}
})
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});
var resp = await manage(this.props.session.userId,this.props.session.ApiKey,"hi","hello");
if (resp.status == 200){
var respBody = await resp.json();
console.log('Fetch Todo response '+respBody);
}
API in separate file
export async function manage(userId,ApiKey,query,query1) {
var url ="http://www.example.com/getdata";
const params = {
search:query,
searches:query1
};
var formBody = [];
for (const property in params) {
const encodedKey = encodeURIComponent(property);
const encodedValue = encodeURIComponent(params[property]);
formBody.push(encodedKey + "=" + encodedValue);
}
formBody = formBody.join("&");
const requestOptions = {
'method': 'POST',
'headers': {
'Content-Type': 'application/x-www-form-urlencoded'
// 'Content-Type': 'application/json'
},
'body': formBody
};
requestOptions.headers["userid"] = userId
requestOptions.headers["apikey"] = ApiKey
try {
var resp = await fetch(url, requestOptions);
return resp;
}
catch (err) {
console.log("Request Failed: " + err);
return err;
}
}

React-Native : How to get callback of api call in another class

I am calling a web service
Here is my code:
var result;
export function callPostApi(urlStr, params)
{
fetch(urlStr, {method: "POST", headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify(params)})
.then((response) => response.json())
.then((responseData) => {
result = JSON.stringify(responseData)
})
.catch((error) => { console.error(error);
Alert.alert('Alert Title failure' + JSON.stringify(error))
})
.done();
return result
}
I am calling from here:
callapi(){
var dict = {
email: 'at#gmail.com',
password: '123456',
}
result = callPostApi('http://demo.com', dict)
}
Currently, it is calling in Async mode that we want but code is written below this method getting execute immediately after calling of above method
i want callback when result from sever has received so that i can execute code written below the above method is execute after receiving response from server.
You need to use Promises.
Change your callPostApi function to return a Promise, then you can chain additional then, catch and finally calls.
export function callPostApi(urlStr, params) {
return fetch(urlStr, {
method: "POST",
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify(params)
})
.then((response) => response.json())
.then((responseData) => {
result = JSON.stringify(responseData)
})
.catch((error) => {
console.error(error);
Alert.alert('Alert Title failure' + JSON.stringify(error))
});
}
callapi() {
callPostApi('http://demo.com', {
email: 'at#gmail.com',
password: '123456',
})
.then((response) => {
// Continue your code here...
});
}

Resources