Post Request message Not being displayed in the App when sending post req from ui front end

I am building a chat app which displays the Name and the message to be sent using node.js ,express.js,socket.io , mongodb

But the below question comes up during the Node.js ,express,js part (socket.io and mongodb not used till now). The question is the code should have displayed the user and message below but in my case it is simply a blank

What i expect enter image description here

SERVER.JS FILE

var express =require("express")

var bodyParser = require("body-parser")

var app = express()

app.use(express.static(__dirname))

app.use(bodyParser.json())

app.use(bodyParser.urlencoded({extended:false}))

var messages=[

    {name: "Dibin",message:"HELLO"},

    {name: "Subin",message:"Hi"}
]

 

app.get('/messages',(req,res)=>{

res.send(messages)

})

app.post('/messages',(req,res)=>{

    messages.push(req.body)

    res.sendStatus(200)
})


var server=app.listen(3010, () => {

console.log("Server is listening on port",server.address().port )

})`
`

INDEX.HTML FILE

<!DOCTYPE html>
<html>
    <head> 
        
        <link rel="stylesheet" 
        href="https://stackpath.bootstrapcdn.com/bootstrap/4.2.1/css/bootstrap.min.css" 
        integrity="sha384-GJzZqFGwb1QTTN6wy59ffF1BuGJpLSa9DkKMp0DgiMDm4iYMj70gZWKYbI706tWS" 
        crossorigin="anonymous">
        <script src="https://code.jquery.com/jquery-3.3.1.min.js" crossorigin="anonymous"></script>
        <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.6/umd/popper.min.js" 
         integrity="sha384-wHAiFfRlMFy6i5SRaxvfOCifBUQy1xHdJ/yoi7FRNXMRBu5WHdZYu1hA6ZOblgut" 
         crossorigin="anonymous"></script>
        <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.2.1/js/bootstrap.min.js" 
         integrity="sha384-B0UglyR+jN6CkvvICOB2joaf5I4l3gm9GU6Hc1og6Ls7i6U/mkkaduKaBhlAXv9k" 
         crossorigin="anonymous"></script>

    </head>   

    <body>

        <div class="container">
        <br>
           <div class="jumbotron">
            <h1 class="display-4"> Send Message </h1>
            <br>
            
            <input id ="name" class="form-control" placeholder ="Name">
            <br>
            <textarea id ="message" class="form-control" placeholder ="Message"></textarea>
            <br>
            <button id="send" class="btn btn-success">Send</button>  
           </div>
        
           <div id="messages">
               
           </div>   
        </div>
         
         
     <script>
         $(()=> {

           $("#send").click(() =>{ 
        
            var message ={name: $("#name").val(), message: $("#message").val()}
            postMessage(message)

         })
        getMessages()
        })

         function addMessages(message){
          
            $("#messages").append(`<h4> ${message.name} </h4> <p> ${message.message}</p>`)


         }

         function getMessages(){

            $.get("http://localhost:3010/messages",data=>{

                console.log(data)
            })
         }


         function postMessage(message) {

            $.post('http://localhost:3010/messages', message )

           }

     </script>

    </body>   

</html>

Answer

Try extended: true

app.use(bodyParser.urlencoded({extended:true}))

From official documentation:

bodyParser.urlencoded([options]) Returns middleware that only parses urlencoded bodies and only looks at requests where the Content-Type header matches the type option. This parser accepts only UTF-8 encoding of the body and supports automatic inflation of gzip and deflate encodings. A new body object containing the parsed data is populated on the request object after the middleware (i.e. req.body). This object will contain key-value pairs, where the value can be a string or array (when extended is false), or any type (when extended is true).

Leave a Reply

Your email address will not be published. Required fields are marked *