简体   繁体   中英

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

I have a express server runnnig on the port 8082. After accessing the route "/" as GET it renders the index.html file, then I send its form to "/" as POST using the app.js script. This route has a middleware called "validate1" that checks if the header "x-client" is equals "student" in order to control this route access.

The problem is that when the header "x-client" is not equals "student", and the "validate1" middleware ends up in the "else", I just can't render or send anything as response. The node.js prints my "here" but it doesn't run its next "res.send()" line.

At the "/travel" route I have pretty much the same middleware working perfectly, but there I am using the GET method and none jquery.

UPDATE: I figured out my response is being printed in my browser console because of my ".then()" at the jquery POST function in "app.js", but even deleting it the response is never displayed at the page.

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

Actually I don't get any error, but instead receiving the message I was supposed my form button just gets disabled and nothing happens.

Thanks in advance.

You are making a POST HTTP call, whereas you are using router.get in your routing.js file.

Can you change your code to something like this:

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

    res.json(user)
})

Make the following changes to app.js to display the reponse message in 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)
    })
})

I believe your page is refreshing? Since the form element itself may be performing a submission, you might try including event.preventDefault() at the top of your click handler. This would explain why your server's else clause is running, but no message is seen client-side.

I'm not sure, but maybe the post expect to json so try to send

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

or set the content-type header to 'text'

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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