首页 > 解决方案 > Node.js - 无法从中间件渲染/发送内容

问题描述

我有一个在端口 8082 上运行的快速服务器。在以 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()”,但即使删除它,响应也不会显示在页面上。

索引.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>

应用程序.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)
    })
})

路由.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!")   
})

实际上我没有收到任何错误,而是收到消息,我认为我的表单按钮只是被禁用并且没有任何反应。

提前致谢。

标签: javascriptjqueryexpresspostmiddleware

解决方案


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

你能把你的代码改成这样:

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)
    })
})

推荐阅读