如何将文件路径作为参数传递给路由器/控制器

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

所以我已经为此苦苦挣扎了很长一段时间。我希望使用 nodeJS / Express 显示特定文件夹中的所有文件。我有这个路由器+控制器。

const router = require('express').Router();

router.get('/getAll/:folder', handleGetAll);

我的控制器看起来像这样

const handleGetImages = async (req, res) => {
    
const user = req.user;
    // Get the folder from the request
const folderPath = req.params[0];


    // Get the images from the database
    const images = await Image.find({ folder: folderPath });


    //Returning all public or user owned images

    const filteredImages = images.filter((image) => {
        // Check if the image is public or if the user owns it
        
    return image.isPublic || (image.user && image.user.toHexString() === user);
      });
      return res.json(filteredImages);

};

在前端,我使用 SWR 来查询我的后端,如下所示:

const {data, error, isLoading} = useSWR(['/images/getAll/'+folder, token], getImages );

还有我的吸气剂:

const getImages = async (props) => {
  const [folder, token] = props;
    const response = await axios.get(BACKEND_PATH+folder, { headers: { Authorization: "Bearer " + token }});
    return response.data;
}

问题是我收到 404 错误,就好像我的路线没有正确匹配,因为文件路径有“/”。

任何帮助将不胜感激

我尝试对我的 url 进行编码,不知何故它会被express自动解码...

node.js reactjs express parameters router
1个回答
0
投票

您似乎正在尝试将文件路径作为参数传递给 Express 路由,并且遇到问题,因为文件路径包含正斜杠(“/”)。默认情况下,Express 将路由参数中的正斜杠视为路由路径的一部分,而不是分隔符。要使用文件路径,您应该对路由参数中的正斜杠进行 URL 编码,然后在控制器中对其进行解码。

具体操作方法如下:

  1. 发送请求之前在客户端(前端)对文件路径进行编码:
const { data, error, isLoading } = useSWR(['/images/getAll/' + encodeURIComponent(folder), token], getImages);
  1. 解码 Express 控制器中的文件路径:
const handleGetImages = async (req, res) => {
  const user = req.user;
  
  // Decode the folder path from the request
  const folderPath = decodeURIComponent(req.params.folder);

  // Rest of your code
  // ...
};

通过在客户端使用

encodeURIComponent
和在服务器端使用
decodeURIComponent
,您可以传递和处理包含正斜杠的文件路径,而不会遇到问题。

确保在代码中一致使用

encodeURIComponent
decodeURIComponent
函数,以便在将文件路径作为路由参数传递时正确处理文件路径。这样,Express 将正确匹配路由并处理文件路径,而不会导致 404 错误。

© www.soinside.com 2019 - 2024. All rights reserved.