Jonas Drotleff Jonas Drotleff - 1 month ago 8
Ajax Question

Express - Do not render POST response

I have a basic Express API:

app.get('/example', function(req, res) {
if (req.body.messageid == 1) {
res.send({message: "Message"});
}
}


All it does is returning a message that should then be displayed on a HTML page.

In order to display the message, I implemented this ajax call with jquery:

$('#view-message').on('click', function() {
$.ajax({
type: "POST",
url: "/example",
data: { messageid: 1},
contentType: "text/json; charset=utf-8",
dataType: "text",
success: function (msg) {
$('#content').text(msg);
},
error: function (err) {
console.log(err);
}
});
});


Instead of displaying the message, it just renders a new page with the content
{message: "Message"}
and not just displays the message in the existing page.

How can I make it not render the result?

Answer

put index.html in public

<!DOCTYPE html>
<html>
<head>
    <title></title>
    <meta charset="utf-8">
</head>
<body>

    <div id="content"></div>

    <script type="text/javascript" src="https://code.jquery.com/jquery-1.12.4.min.js"></script>

    <script>
    $.ajax
    ({
        type: "POST",
        url: "http://localhost:8080/example",
        data: { messageid: 1},
        dataType: "json",
        cache : false,
        success: function (data) {
            $('#content').text(data.message);
        },
        error: function (err) {
          console.log(err);
        }
    });
    </script>
</body>
</html>

and in index.js

var express = require('express');
var bodyParser = require('body-parser');
var path = require('path');

var app = express();

app.use(express.static(path.join(__dirname, 'public')));

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

app.post('/example', function(req, res) {
  if (req.body.messageid == 1) {
    res.send({message: "Message"});
  }
});

app.listen(8080);

it works

Comments