Axios headers work for Django GET request, but not PUT request











up vote
0
down vote

favorite












I can sucessfully make a GET request on my /rest-auth/user/ api with axios and this header



{headers: { 'authorization': `Token ${token}`}}


But when I try to make a PUT request, I get 401 unauthorized. This is the full code of my request:



export const addCountry = (countries) => {
const token = localStorage.getItem('token');
return dispatch => {
dispatch(addCountryPending());
axios.put(
'http://localhost:8000/api/v1/rest-auth/user/',
{headers: { 'authorization': `Token ${token}`}},
{countries: countries}
)
.then(response => {
const user = response.data;
dispatch(addCountryFulfilled(user));
})
.catch(err => {
dispatch(addCountryRejected(err));
})
}
}


and my Django permissions are set as



REST_FRAMEWORK = {
'DEFAULT_AUTHENTICATION_CLASSES': [
'rest_framework.authentication.TokenAuthentication',
],


Does anyone know what I'm doing wrong? Thanks!



edit: The view is the default /rest-auth/user/ view, but I customized the serializer to look like this:



class UserDetailSerializer(UserDetailsSerializer):
countries = serializers.SlugRelatedField(
many=True, slug_field='name',
queryset=Country.objects.all().order_by('pk')
)
count = serializers.IntegerField(read_only=True)

class Meta:
model = User
fields = ('pk', 'username', 'email', 'count', 'countries')


and I have a custom user model:



class User(AbstractUser):
countries = models.ManyToManyField(Country, blank=True)
count = models.IntegerField(blank=True, default=0)

def save(self, *args, **kwargs):
# Must save model before Many To Many relationship can be used.
super(User, self).save(*args, **kwargs)
self.count = self.countries.count()
super(User, self).save(*args, **kwargs)


I'm trying to send a PUT request with a country to add that country to the country list for the authenticated user.










share|improve this question
























  • can you add the corresponding view?
    – JPG
    Nov 8 at 10:28












  • @JPG unfortunately it's the default /rest-auth/user/ view, but I added my user model and serializer
    – peter176
    Nov 8 at 10:54















up vote
0
down vote

favorite












I can sucessfully make a GET request on my /rest-auth/user/ api with axios and this header



{headers: { 'authorization': `Token ${token}`}}


But when I try to make a PUT request, I get 401 unauthorized. This is the full code of my request:



export const addCountry = (countries) => {
const token = localStorage.getItem('token');
return dispatch => {
dispatch(addCountryPending());
axios.put(
'http://localhost:8000/api/v1/rest-auth/user/',
{headers: { 'authorization': `Token ${token}`}},
{countries: countries}
)
.then(response => {
const user = response.data;
dispatch(addCountryFulfilled(user));
})
.catch(err => {
dispatch(addCountryRejected(err));
})
}
}


and my Django permissions are set as



REST_FRAMEWORK = {
'DEFAULT_AUTHENTICATION_CLASSES': [
'rest_framework.authentication.TokenAuthentication',
],


Does anyone know what I'm doing wrong? Thanks!



edit: The view is the default /rest-auth/user/ view, but I customized the serializer to look like this:



class UserDetailSerializer(UserDetailsSerializer):
countries = serializers.SlugRelatedField(
many=True, slug_field='name',
queryset=Country.objects.all().order_by('pk')
)
count = serializers.IntegerField(read_only=True)

class Meta:
model = User
fields = ('pk', 'username', 'email', 'count', 'countries')


and I have a custom user model:



class User(AbstractUser):
countries = models.ManyToManyField(Country, blank=True)
count = models.IntegerField(blank=True, default=0)

def save(self, *args, **kwargs):
# Must save model before Many To Many relationship can be used.
super(User, self).save(*args, **kwargs)
self.count = self.countries.count()
super(User, self).save(*args, **kwargs)


I'm trying to send a PUT request with a country to add that country to the country list for the authenticated user.










share|improve this question
























  • can you add the corresponding view?
    – JPG
    Nov 8 at 10:28












  • @JPG unfortunately it's the default /rest-auth/user/ view, but I added my user model and serializer
    – peter176
    Nov 8 at 10:54













up vote
0
down vote

favorite









up vote
0
down vote

favorite











I can sucessfully make a GET request on my /rest-auth/user/ api with axios and this header



{headers: { 'authorization': `Token ${token}`}}


But when I try to make a PUT request, I get 401 unauthorized. This is the full code of my request:



export const addCountry = (countries) => {
const token = localStorage.getItem('token');
return dispatch => {
dispatch(addCountryPending());
axios.put(
'http://localhost:8000/api/v1/rest-auth/user/',
{headers: { 'authorization': `Token ${token}`}},
{countries: countries}
)
.then(response => {
const user = response.data;
dispatch(addCountryFulfilled(user));
})
.catch(err => {
dispatch(addCountryRejected(err));
})
}
}


and my Django permissions are set as



REST_FRAMEWORK = {
'DEFAULT_AUTHENTICATION_CLASSES': [
'rest_framework.authentication.TokenAuthentication',
],


Does anyone know what I'm doing wrong? Thanks!



edit: The view is the default /rest-auth/user/ view, but I customized the serializer to look like this:



class UserDetailSerializer(UserDetailsSerializer):
countries = serializers.SlugRelatedField(
many=True, slug_field='name',
queryset=Country.objects.all().order_by('pk')
)
count = serializers.IntegerField(read_only=True)

class Meta:
model = User
fields = ('pk', 'username', 'email', 'count', 'countries')


and I have a custom user model:



class User(AbstractUser):
countries = models.ManyToManyField(Country, blank=True)
count = models.IntegerField(blank=True, default=0)

def save(self, *args, **kwargs):
# Must save model before Many To Many relationship can be used.
super(User, self).save(*args, **kwargs)
self.count = self.countries.count()
super(User, self).save(*args, **kwargs)


I'm trying to send a PUT request with a country to add that country to the country list for the authenticated user.










share|improve this question















I can sucessfully make a GET request on my /rest-auth/user/ api with axios and this header



{headers: { 'authorization': `Token ${token}`}}


But when I try to make a PUT request, I get 401 unauthorized. This is the full code of my request:



export const addCountry = (countries) => {
const token = localStorage.getItem('token');
return dispatch => {
dispatch(addCountryPending());
axios.put(
'http://localhost:8000/api/v1/rest-auth/user/',
{headers: { 'authorization': `Token ${token}`}},
{countries: countries}
)
.then(response => {
const user = response.data;
dispatch(addCountryFulfilled(user));
})
.catch(err => {
dispatch(addCountryRejected(err));
})
}
}


and my Django permissions are set as



REST_FRAMEWORK = {
'DEFAULT_AUTHENTICATION_CLASSES': [
'rest_framework.authentication.TokenAuthentication',
],


Does anyone know what I'm doing wrong? Thanks!



edit: The view is the default /rest-auth/user/ view, but I customized the serializer to look like this:



class UserDetailSerializer(UserDetailsSerializer):
countries = serializers.SlugRelatedField(
many=True, slug_field='name',
queryset=Country.objects.all().order_by('pk')
)
count = serializers.IntegerField(read_only=True)

class Meta:
model = User
fields = ('pk', 'username', 'email', 'count', 'countries')


and I have a custom user model:



class User(AbstractUser):
countries = models.ManyToManyField(Country, blank=True)
count = models.IntegerField(blank=True, default=0)

def save(self, *args, **kwargs):
# Must save model before Many To Many relationship can be used.
super(User, self).save(*args, **kwargs)
self.count = self.countries.count()
super(User, self).save(*args, **kwargs)


I'm trying to send a PUT request with a country to add that country to the country list for the authenticated user.







django reactjs django-rest-framework axios






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Nov 8 at 10:42

























asked Nov 8 at 8:28









peter176

178




178












  • can you add the corresponding view?
    – JPG
    Nov 8 at 10:28












  • @JPG unfortunately it's the default /rest-auth/user/ view, but I added my user model and serializer
    – peter176
    Nov 8 at 10:54


















  • can you add the corresponding view?
    – JPG
    Nov 8 at 10:28












  • @JPG unfortunately it's the default /rest-auth/user/ view, but I added my user model and serializer
    – peter176
    Nov 8 at 10:54
















can you add the corresponding view?
– JPG
Nov 8 at 10:28






can you add the corresponding view?
– JPG
Nov 8 at 10:28














@JPG unfortunately it's the default /rest-auth/user/ view, but I added my user model and serializer
– peter176
Nov 8 at 10:54




@JPG unfortunately it's the default /rest-auth/user/ view, but I added my user model and serializer
– peter176
Nov 8 at 10:54












1 Answer
1






active

oldest

votes

















up vote
0
down vote



accepted










In axios functions get and put has different semantics. The get functions get configuration object like the second parameter:



axios.get(url[, config])


And the put function like the third parameter:



axios.put(url[, data[, config]])


So you should add your headers like this:



axios.put(
'http://localhost:8000/api/v1/rest-auth/user/',
{}, // data
{
countries: countries,
headers: { 'authorization': `Token ${token}`},
}
)





share|improve this answer





















  • Thanks, solves everything
    – peter176
    Nov 8 at 17:26











Your Answer






StackExchange.ifUsing("editor", function () {
StackExchange.using("externalEditor", function () {
StackExchange.using("snippets", function () {
StackExchange.snippets.init();
});
});
}, "code-snippets");

StackExchange.ready(function() {
var channelOptions = {
tags: "".split(" "),
id: "1"
};
initTagRenderer("".split(" "), "".split(" "), channelOptions);

StackExchange.using("externalEditor", function() {
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled) {
StackExchange.using("snippets", function() {
createEditor();
});
}
else {
createEditor();
}
});

function createEditor() {
StackExchange.prepareEditor({
heartbeatType: 'answer',
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader: {
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
},
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
});


}
});














 

draft saved


draft discarded


















StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53203895%2faxios-headers-work-for-django-get-request-but-not-put-request%23new-answer', 'question_page');
}
);

Post as a guest
































1 Answer
1






active

oldest

votes








1 Answer
1






active

oldest

votes









active

oldest

votes






active

oldest

votes








up vote
0
down vote



accepted










In axios functions get and put has different semantics. The get functions get configuration object like the second parameter:



axios.get(url[, config])


And the put function like the third parameter:



axios.put(url[, data[, config]])


So you should add your headers like this:



axios.put(
'http://localhost:8000/api/v1/rest-auth/user/',
{}, // data
{
countries: countries,
headers: { 'authorization': `Token ${token}`},
}
)





share|improve this answer





















  • Thanks, solves everything
    – peter176
    Nov 8 at 17:26















up vote
0
down vote



accepted










In axios functions get and put has different semantics. The get functions get configuration object like the second parameter:



axios.get(url[, config])


And the put function like the third parameter:



axios.put(url[, data[, config]])


So you should add your headers like this:



axios.put(
'http://localhost:8000/api/v1/rest-auth/user/',
{}, // data
{
countries: countries,
headers: { 'authorization': `Token ${token}`},
}
)





share|improve this answer





















  • Thanks, solves everything
    – peter176
    Nov 8 at 17:26













up vote
0
down vote



accepted







up vote
0
down vote



accepted






In axios functions get and put has different semantics. The get functions get configuration object like the second parameter:



axios.get(url[, config])


And the put function like the third parameter:



axios.put(url[, data[, config]])


So you should add your headers like this:



axios.put(
'http://localhost:8000/api/v1/rest-auth/user/',
{}, // data
{
countries: countries,
headers: { 'authorization': `Token ${token}`},
}
)





share|improve this answer












In axios functions get and put has different semantics. The get functions get configuration object like the second parameter:



axios.get(url[, config])


And the put function like the third parameter:



axios.put(url[, data[, config]])


So you should add your headers like this:



axios.put(
'http://localhost:8000/api/v1/rest-auth/user/',
{}, // data
{
countries: countries,
headers: { 'authorization': `Token ${token}`},
}
)






share|improve this answer












share|improve this answer



share|improve this answer










answered Nov 8 at 16:35









Iwan

1,4191021




1,4191021












  • Thanks, solves everything
    – peter176
    Nov 8 at 17:26


















  • Thanks, solves everything
    – peter176
    Nov 8 at 17:26
















Thanks, solves everything
– peter176
Nov 8 at 17:26




Thanks, solves everything
– peter176
Nov 8 at 17:26


















 

draft saved


draft discarded



















































 


draft saved


draft discarded














StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53203895%2faxios-headers-work-for-django-get-request-but-not-put-request%23new-answer', 'question_page');
}
);

Post as a guest




















































































Popular posts from this blog

Schultheiß

Liste der Kulturdenkmale in Wilsdruff

Android Play Services Check