我可以使用axios和此标头在/ rest-auth / user / api上成功发出GET请求
{headers: { 'authorization': `Token ${token}`}}
但是当我尝试发出PUT请求时,我得到401未经授权。这是我请求的完整代码:
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));
})
}
}
,我的Django权限设置为
REST_FRAMEWORK = {
'DEFAULT_AUTHENTICATION_CLASSES': [
'rest_framework.authentication.TokenAuthentication',
],
有人知道我在做什么错吗?谢谢!
edit:该视图是默认的/ rest-auth / user /视图,但是我自定义了序列化器,如下所示:
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')
,我有一个自定义用户模型:
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)
我正在尝试向一个国家/地区发送PUT请求,以将该国家/地区添加到已认证用户的国家/地区列表中。
答案 0 :(得分:1)
在axios函数中,get
和put
具有不同的语义。 get
函数会像第二个参数一样获取配置对象:
axios.get(url[, config])
put
函数类似于第三个参数:
axios.put(url[, data[, config]])
所以您应该这样添加标题:
axios.put(
'http://localhost:8000/api/v1/rest-auth/user/',
{}, // data
{
countries: countries,
headers: { 'authorization': `Token ${token}`},
}
)