Node.js在错误404上将用户重定向到主页

时间:2019-08-04 18:45:29

标签: node.js ajax express

[更新]问题已解决。下面的代码是有效的版本。

我试图将用户重定向回首页,以防他们输入了错误的URL。在快速代码中,我创建了一个函数,用于将用户临时数据保存在localhost:8000 / users文件夹中。

My file structure is:
Data/data.html (added on [Update] for temporarily storing the data) 
node_modules
static
static/index.html
static/JS/script.js
app.js
package-lock.json
package.json

这是index.html代码:

<!DOCTYPE html>
<html>
<head>
    <title>Sending data to and from the server</title>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
</head>
<body>
    <div>
        <h4 id="log1"></h4>
    </div>
    <input id="grab1" type="text">
    <input id="press1" type="button" value="Send">
    <input id="show1" type="button" value="Show">
    <div id="output1"></div>
    <script src="./JS/script.js"></script>
</body>
</html>

这是script.js:

$(document).ready(function () {

    // Ajax fuction for sending data
    function send(data) {
        $.ajax({
            type: "POST",
            url: "http://localhost:8000",
            crossDomain: true,
            dataType: "string",
            data: data
        })
    }

    //Sending Data to the server
    $("#press1").on("click", () => {
        send({
            data: $("#grab1").val()
        })
        $("#log1").html("Successfully sent")
    });

    //Showing Output received from the server
    $("#show1").on("click", () => {
        $.get("/users", (data) => {
            $("#output1").html(`<h3>${ data }</h3>`);
        });
    });
});

[更新]这是服务器端app.js脚本的工作版本。

    // Importing Modules
const express = require("express")
const path = require("path")
const app = express();
const bodyParser = require("body-parser")
const fs = require("fs")

// Using bodyParser and setting localhost directory to static
app.use(bodyParser.urlencoded({
    extended: false
}))
app.use('/', express.static(path.join(__dirname, 'static')));
app.use('/users', express.static(path.join(__dirname, 'Data', "data.html")));



// Post1 listens to all incoming posts 
function Post1() {
    app.post("/*", (postRequest, postResponse) => {
        // if it's localhost:8000 than then following function will run for 
        // the post and so on for each url.
        if (postRequest.headers.referer == "http://localhost:8000/") {
            // bigP1 is the string received from the ajax function
            bigP1 = postRequest.body.data;
            fs.writeFile("./Data/data.html", `${ bigP1 }`, (err) => {
                if (err) {
                    console.log(err);
                } else {
                    console.log("done");
                }
            })
        }
        // It's the same function for else (at least for now)
        else if (postRequest.headers.referer == "http://localhost:8000/index.html") {
            bigP1 = postRequest.body.data;
            fs.writeFile("./Data/data.html", `${ bigP1 }`, (err) => {
                if (err) {
                    console.log(err);
                } else {
                    console.log("done");
                }
            })
        }
        // If the post path is unidentified than the following is 
        // sent.    
        else {
            res.send(`<h1>${req.params.name} is not a website</h1>\n<a href="http://localhost:8000/">Go back</a>`)
        }
    })
}
// running Post1 here
Post1()


app.get("/*", (req, res) => {
    res.send(`<h1>${ req.params.name } is not a website</h1>\n<a href="http://localhost:8000/">Go back</a>`);
})

app.listen(8000)

感谢您的观看。

1 个答案:

答案 0 :(得分:0)

我认为这可能会发生两件事。

  • 如果您还希望允许 localhost:8000 / 作为 header.referrer 的有效路径,则可以执行
    if (postRequest.headers.referer == "http://localhost:8000/" ||
        postRequest.headers.referer == "localhost:8000/" ) {
         ...
        }
  • 但是,如果问题出在重定向本身,则可能是您正在尝试使用AJAX重定向某人,而这种方法不会发生。

在这种情况下,您可以在响应中包含一个包含

之类的对象
{status : "succes", redirect: ""} or {status: "fail", redirect: "http://localhost:8000}" 

然后您可以在yout脚本中拥有一个搜索状态并在找到“ fail” 运行时的函数

window.location = redirect;

如果您想扩展这种解决方案,可以查看以下答案:https://stackoverflow.com/a/41078774/11280510

另一方面,如果您试图避免某些情况,例如有人可以检索您在网络外发出的请求的信息,则可以使用 content-policy-header 。 >

有关此信息的更多信息:https://content-security-policy.com/