当我尝试使用带有post请求的表单将图像上传到后端时,我得到一个403错误。我尝试添加X-CSRFToken和"Accept";application/json"对于头来说,这一点帮助都没有。我试图将保存到本地存储的名称的所有者添加到postBody我不知道我哪里出错了。我使用j-rest-auth进行身份验证有从前端获取函数:
export async function action({ request }) {
const data = await request.formData();
// const file = fileToBase64(data.get('file'))
console.log(data)
const postData = {
title: data.get('title'),
image: data.get('base64File'),
};
console.log(postData)
const response = await fetch('http://127.0.0.1:8000/posts', {
method: 'POST',
headers: {
"Content-Type": "application/json"
},
body: JSON.stringify(postData),
});
if (response.status === 422 || response.status === 401) {
return response;
}
if (!response.ok) {
throw json({ message: 'Could not add image.' }, { status: 500 });
}
const resData = await response.json();
console.log(resData)
return redirect('/');
}
有后端序列化器:
class PostsSerializer(serializers.HyperlinkedModelSerializer):
title = serializers.CharField(max_length=60, )
owner = serializers.ReadOnlyField(source='owner.username')
# creator_id = UserSerializer(many=False, read_only=True).data
favorites = serializers.HyperlinkedRelatedField(many=True, read_only=True, view_name='favorite-detail')
comments = serializers.HyperlinkedRelatedField(many=True, read_only=True, view_name='comment-detail')
class Meta:
model = Post
fields = ['pk', 'url', 'title', 'owner', 'image', 'created_at', 'favorites', 'comments']
和观点:
class PostList(generics.ListCreateAPIView):
permission_classes = [permissions.IsAuthenticatedOrReadOnly, IsCurrentUserOwnerOrReadOnly]
queryset = Post.objects.all()
serializer_class = PostsSerializer
ordering_fields = ['created_at', 'favorites']
filter_fields = ['title']
search_fields = ['title']
name = 'post-list'
def perform_create(self, serializer):
serializer.save(owner=self.request.user)
如果你需要完整的代码,这里有一个到仓库的链接:https://github.com/Cichyy22/imagur-like-site
包含一个类型为"file"在表单中允许用户选择要上传的图像文件。
<form action="/upload" method="post" enctype="multipart/form-data">
<input type="file" name="image">
<input type="submit" value="Upload">
</form>
const express = require('express');
const multer = require('multer');
const app = express();
// Configure multer to store uploaded files in the "uploads" directory
const upload = multer({ dest: 'uploads/' });
// Handle the POST request to upload an image
app.post('/upload', upload.single('image'), (req, res) => {
const image = req.file;
// Do something with the uploaded image file
res.send('Image uploaded successfully');
});
我通过编辑请求来解决这个问题:
export async function action({ request }) {
const data = await request.formData();
// const file = fileToBase64(data.get('file'))
console.log(data)
const postData = {
title: data.get('title'),
image: data.get('base64File')
};
console.log(postData)
const response = await fetch('http://127.0.0.1:8000/posts', {
method: 'POST',
headers: {
'Authorization': 'Token ' + localStorage.getItem('token'),
"X-CSRFToken": Cookies.get('csrftoken'),
"Accept": "application/json",
"Content-Type": "application/json"
},
body: JSON.stringify(postData),
});
if (response.status === 422 || response.status === 401) {
return response;
}
if (!response.ok) {
throw json({ message: 'Could not add image.' }, { status: 500 });
}
const resData = await response.json();
console.log(resData)
return redirect('/');
}
并通过编辑后端设置文件:
REST_FRAMEWORK = {
'DEFAULT_FILTER_BACKENDS': (
'django_filters.rest_framework.DjangoFilterBackend',
'rest_framework.filters.OrderingFilter',
'rest_framework.filters.SearchFilter',
),
'DEFAULT_AUTHENTICATION_CLASSES': (
'rest_framework.authentication.TokenAuthentication',
'rest_framework.authentication.SessionAuthentication',
)
}
REST_USE_JWT = True
JWT_AUTH_COOKIE_USE_CSRF = True