繁体   English   中英

Node.js-无法渲染/发送来自中间件的内容

[英]Node.js - Can't render/send something from middleware

我在端口8082上有一个快速服务器runnnig。以GET方式访问路由“ /”后,它将呈现index.html文件,然后使用app.js脚本以POST形式将其形式发送到“ /”。 该路由具有称为“ validate1”的中间件,该中间件检查报头“ x-client”是否等于“ student”,以便控制此路由访问。

问题是,当标头“ x-client”不等于“ student”,并且“ validate1”中间件以“ else”结尾时,我只是无法呈现或发送任何内容作为响应。 node.js打印我的“这里”,但不运行其下一个“ res.send()”行。

在“ / travel”路线上,我有几乎相同的中间件可以正常工作,但是在这里我使用的是GET方法,没有jquery。

更新:我发现我的响应在我的浏览器控制台中被打印,这是因为我在“ app.js”中的jQuery POST函数中使用了“ .then()”,但是即使删除它,该响应也永远不会显示在页面上。

index.html

<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge"><!-- rota no css-->
    <title>Document</title>

    <link rel="stylesheet" href="./style.css">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>

</head>
<body>
    <form method="POST">
        Nome:<input name="nome" type="text" id="nome">
        <br>
        Sobrenome:<input name="sobrenome" type="text" id="sobrenome">
        <button>Send data</button>
    </form>

</body>

<script src="./app.js"></script>
</html>

app.js

$("button").on("click", (event) => {
    $("button").attr("disabled","disabled")
    const nome = $("#nome").val().trim()
    const sobrenome = $("#sobrenome").val().trim()

    const user = {
        nome,
        sobrenome
    }

    $.ajax({
        url:"/",
        method:"POST",
        data:user,
        headers:{
            "x-client":"student",
            "x-class":500
        }
    }).then((resposta) => {
        console.log(resposta)
    }).catch((erro) => {
        console.log("Error:" + erro)
    })
})

routing.js

const express = require("express")
const path = require("path")entre windows e mac

const router = express.Router()

router.get("/",(req,res) => {
    res.sendFile(path.join(__dirname,"../views/index.html"))
})

//not working route
const validate1 = (req,res,next) => {
    const access = req.headers["x-client"]
    if(access === "student2"){
        next()
    }
    else{
        console.log("here")//it runs!
        res.send("You don't have access to it!")//it doesn't run!
    }
}

router.post("/", validate1 ,(req,res) => {
    const user = {
        nome:req.body.nome,
        sobrenome: req.body.sobrenome
    }

    res.json(user)
})

//working route

const validate2 = (req,res,next) => {
    const access = false
    if(access){
        next()
    }
    else{
        res.send("You don't have access to it!")  
    }
}

router.get("/travel",validate2,(req,res) => {
    res.send("Travel!")   
})

实际上,我没有收到任何错误,但是收到消息后,我以为我的表单按钮被禁用了,什么也没发生。

提前致谢。

您正在进行POST HTTP调用,而在routing.js文件中使用router.get

您可以将代码更改为以下内容吗:

router.post("/", validate1 ,(req,res) => {
    const user = {
        nome:req.body.nome,
        sobrenome: req.body.sobrenome
    }

    res.json(user)
})

对app.js进行以下更改,以在index.html中显示响应消息

$("button").on("click", (event) => {
    $("button").attr("disabled","disabled")
    const nome = $("#nome").val().trim()
    const sobrenome = $("#sobrenome").val().trim()

    const user = {
        nome,
        sobrenome
    }

    $.ajax({
        url:"/",
        method:"POST",
        data:user,
        headers:{
            "x-client":"student",
            "x-class":500
        }
    }).then((resposta) => {
        console.log(resposta)
        $('body').append(resposta);
    }).catch((erro) => {
        console.log("Error:" + erro)
    })
})

我相信您的页面令人耳目一新? 由于表单元素本身可能正在执行提交,因此您可以尝试在点击处理程序的顶部包含event.preventDefault() 这可以解释为什么服务器的else子句正在运行,但是客户端看不到任何消息。

我不确定,但也许该帖子期望发送到json,所以请尝试发送

res.send({msg:'some msg'});

或将内容类型标头设置为“文本”

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM