Express - 不要呈现POST响应

时间:2016-10-18 16:40:56

标签: javascript jquery ajax node.js express

我有一个基本的Express API:

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

它只是返回一条消息,然后应该在HTML页面上显示。

为了显示消息,我用jquery:

实现了这个ajax调用
$('#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);
    }
  });
});

它不是显示消息,而是呈现包含内容{message: "Message"}的新页面,而不只是在现有页面中显示消息。

如何让它不呈现结果?

1 个答案:

答案 0 :(得分:1)

index.html放入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>

并在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);

有效