【问题标题】:How to access variable stored in POST into GET fnction?如何将存储在 POST 中的变量访问到 GET 函数中?
【发布时间】:2020-12-28 21:40:17
【问题描述】:

我的 post 方法是我用来上传文件并将它们存储在本地目录中的文件夹中的 API 的一部分。当用户上传文件时,它会存储在本地目录中,并且图像的路径会记录在控制台中。我正在尝试将 POST 方法中记录的路径渲染到我在 get 路由中渲染的 EJS 模板。我是新来表达和节点有什么办法可以做到这一点?这是我的代码:

const storage = multer.diskStorage({
    destination: './upload/images',
    filename: (req, file, cb) => {
        return cb(null, `${file.fieldname}_${Date.now()}${path.extname(file.originalname)}`)
    }
})

const upload = multer({
    storage: storage,
   limits:{
       fileSize: 10485760
   }
})

app.post("/upload", upload.single('profile'), (req, res) => {
    res.redirect("/main")
    let imgPath = req.file.path;
    console.log(imgPath);
})

function errHandler(err, req, res, next) {
    if (err instanceof multer.MulterError) {
        res.json({
            success: 0,
            message: err.message
        })
    }
}
app.use(errHandler);

此日志 “upload\images\profile_1609158104360.jpg”

我的 get 函数试图从 /upload 发布路径访问记录的路径

app.get("/main", function  (req, res) {
    if (req.isAuthenticated()) {
        // res.render("main");
        User.find({ "secret": {$ne: null}}, function(err, foundUser, imgPath){
            if(err){
                console.log(err);
            }else{
                if(foundUser){
                    res.render("main", {
                        usersWithSecrets: foundUser,
                        usersWithImage: imgPath
                    });
                    console.log(imgPath);
                }
            }
        }
        );
    } else {
        res.redirect("/login");
    }

});

【问题讨论】:

    标签: node.js express post ejs


    【解决方案1】:

    你不能。在发布/上传时,您返回重定向。与浏览器发出的 get /main 相比,这是完全不同的请求。

    【讨论】:

    • 有什么办法可以做到吗?我之前尝试过 res.json,但也没有用。
    • 它的另一个请求,除非你以某种方式创建它,否则它与以前的请求没有任何联系。通过查看您的代码,我可以判断您正在保存个人资料图片。保存图片时,可以将头像路径保存到数据库,解决所有问题。
    • 非常感谢我的朋友,我现在就试试看是否有效:) 非常感谢您的帮助
    猜你喜欢
    • 1970-01-01
    • 2022-11-11
    • 2019-06-16
    • 2023-04-03
    • 2017-11-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多