我可以使用 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',
],
有谁知道我做错了什么?谢谢!
编辑:该视图是默认的 /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 请求,以将该国家/地区添加到经过身份验证的用户的国家/地区列表中。
在 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}`},
}
)
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句