首页 > 解决方案 > 如何使用 Express 发布路由将客户端重定向到新页面?

问题描述

我正在尝试构建一个节点/express webapp,在其中单击一个将a<div>转换为pdf的按钮,zip和密码保护pdf,将其通过电子邮件发送给收件人,最后生成一个带有pdf的新页面,以便我可以看到它正确呈现。

除了生成 pdf 的预览之外,我一切正常。一般来说,我对节点和 http 路由很陌生,所以我知道我遗漏了一些明显的东西。

表单成功发送<div>到服务器,服务器对其进行转换、压缩并成功发送。/public/pdfs它还会在目录中保存 pdf 的副本。我确实确保包含app.use(express.static(path.join(__dirname, 'public')));静态目录。我可以通过直接在浏览器中输入pdf来访问它,但是在我将它提交到服务器后我无法让它自动加载。

浏览器窗口显示:

Cannot GET /pdfs/2018_5_5_wj.pdf

浏览器控制台显示:

Failed to load resource: the server responded with a status of 404 (Not Found)

Refused to apply a stylesheet because its hash, its nonce, or 'unsafe-inline' appears in neither the style-src directive nor the default-src directive of the Content Security Policy.

我可以刷新页面,它完美地在浏览器中显示 pdf。发送重定向(瞬时)和生成 pdf(需要几毫秒)之间是否存在某种时间问题?

(客户)

$("#testPostButton").click(function () {
    fileName = fileNamer();
    var formText = $("#formText").html();
    $.ajax({
        url: '/', 
        type: 'POST', 
        contentType: 'application/json', 
        data: JSON.stringify({formText:formText,fileName:fileName}),
        success: function(data) {
           console.log(data.fileURL);
           setTimeout(function(){window.location = data.fileURL},2000);      
        }
    });             
});

(服务器)

app.post('/', function (req, res) {
    //console.log(req.body);
    formText = req.body['formText'];
    fileName = req.body['fileName'];
    console.log(fileName)
    //console.log(formText);
    var wkhtmltopdf = require('wkhtmltopdf');
    options = {
        'page-size': 'Letter',
        'margin-top': '0.75in',
        'margin-right': '0.75in',
        'margin-bottom': '0.75in',
        'margin-left': '0.75in',
        'encoding': "UTF-8",
        'dpi': 800,
        'output': './public/pdfs/' + fileName,
    };
    wkhtmltopdf(formText, options);

    console.log('pdf generated');

    zipName = zipFile(fileName);
    console.log('zip generated:' + zipName);

    emailFile();


    var data = JSON.stringify({fileURL:'http://localhost:3000/pdfs/'+fileName});
    res.contentType('application/json');
    res.header('Content-Length', data.length);
    res.end(data);

});

标签: javascriptnode.jsexpress

解决方案


好吧,事实证明这是一个时间问题。我在 window.location 命令周围放置了一个 2 秒超时功能,现在它可以工作了。

setTimeout(function(){window.location = data.fileURL},2000);

我尝试了 1 秒,但仍然出现相同的错误,所以事实证明 wkhtmltopdf 需要不到 2 秒的时间来呈现文件。


推荐阅读