Laravel API 和 React 前端:在 404 中提交帖子结果后重定向到个人资料 |未找到

问题描述 投票:0回答:1

我构建了一个 Web 应用程序,其中前端使用 React 创建,后端使用 Laravel 创建。我的应用程序设置如下:

在我的本地环境中一切正常,但部署到实时服务器后,我遇到了问题。当用户提交帖子时,我想将他们导航到他们的个人资料(

https://example.com/user/my-account
)。然而,提交后,用户被重定向到个人资料页面,但却导致了
404 | not found (Oops, looks like the page is lost.)
错误。

预期行为:

提交帖子后,用户应该被重定向到他们的个人资料页面:

https://example.com/user/my-account

相关代码:

Laravel

store
方法

public function store(Request $request)
    {
        try {
            // Validation rules
            $validatedData = $request->validate([
                'content' => 'nullable|string|min:1|max:5000|required_without_all:image', // Content is required without an image, must be at least 1 character if provided
                'image' => 'nullable|image|mimes:jpeg,png,jpg,gif,webp|max:2048|required_without_all:content', // Image is required without content
            ], [
                'content.required_without_all' => 'Please provide content or an image for your post.',
                'content.min' => 'The content must be at least 1 character.',
                'content.max' => 'The post content cannot exceed 5000 characters.',

                'image.required_without_all' => 'Please provide content or an image for your post.',
                'image.image' => 'The uploaded file must be an image.',
                'image.mimes' => 'The image must be a file of type: jpeg, png, jpg, gif.',
                'image.max' => 'The image may not be greater than 2MB.',
            ]);

            $authUser = $request->user()->id;
            // If validation passes, store the post
            $post = new Post();
            $post->user_id = $authUser;
            $post->unique_post_id = Str::uuid();
            $post->point_deduction = 10;
            $post->content = $validatedData['content'] ?? null;

            // Save the image if provided
            if ($request->hasFile('image')) {
                // Get the uploaded image file
                $image = $request->file('image');
                // Generate a new file name using UUID and keep the original extension
                $fileName = Str::uuid() . '.' . $image->getClientOriginalExtension();
                $image->move(public_path('images/'), $fileName);

                // Save the path to the post
                $post->image = $request->root() . '/images' . '/' . $fileName;
            }

            $post->save();            

            return response()->json([
                'message' => 'Post created successfully',
                'post' => $post
            ], 201);
        } catch (ValidationException $e) {
            // Custom error response if validation fails
            return response()->json([
                'message' => 'Validation Failed',
                'errors' => $e->errors(),
            ], 422);
        }

    }

图像存储在子域(管理)图像文件夹中,路径如下:

public_html/admin/public/images/58fd9c5a-a9e2-4f0e-9252-d7538cab1104.jpg
。图像 URL 以
image
形式保存在
posts
表的
https://admin.abc.com/images/58fd9c5a-a9e2-4f0e-9252-d7538cab1104.jpg
列中。但是,当尝试通过此 URL 访问图像时,会导致
404 | Not found
错误,并且图像不会显示。当我收到所有帖子时,图像没有显示在前端。

反应代码

处理提交后:

const handlePostSubmit = async () => {
    setLoading(true);
    const formData = new FormData();
    formData.append("content", postText);
    if (selectedImage?.file) {
        formData.append("image", selectedImage.file);
    }

    try {
        const response = await axios.post(`/me/posts/store`, formData, {
            headers: {
                "Content-Type": "multipart/form-data",
                Authorization: `Bearer ${authToken}`,
            },
        });

        setPostText("");
        setSelectedImage(null);
        navigate("/user/my-account");
        window.location.reload(); // Refresh after redirection to profile
    } catch (error) {
        console.error("Error creating post", error);
    } finally {
        setLoading(false);
    }
};

const ProtectedAuthRoute = ({ element }) => {
    const { isAuthenticated } = useSelector((state) => state.auth);
    return isAuthenticated ? <Navigate to="/" /> : element;
};

<Route
    path="/user/my-account"
    element={
        <ProtectedRoute
            element={<MyAccount />}
        />
    }
/>
reactjs laravel file-upload http-status-code-404 laravel-api
1个回答
0
投票

通常这是网络服务器配置不正确的结果。根目录应该是您的

public
目录,而不是 Laravel 项目根目录。

在您的情况下,您的 Laravel 项目的根目录是

public_html/admin
,但您的网络服务器配置的根目录应该是
public_html/admin/public

Apache 的修复方法是更改此内容:

<VirtualHost *:80>

        ...
    
        DocumentRoot /blah/blah/blah/public_html/admin

        ...

</VirtualHost>

对此:

<VirtualHost *:80>

        ...
    
        DocumentRoot /blah/blah/blah/public_html/admin/public

        ...

</VirtualHost>
© www.soinside.com 2019 - 2024. All rights reserved.