Dojo Ajax请求到节点服务器

时间:2017-06-26 21:26:13

标签: node.js ajax dojo

我正在尝试使用我的客户端中的dojo库向节点服务器发出ajax请求。到目前为止,我无法让Node服务器从我的Dojo请求中提取值。我计划使用此值,并在节点服务器上处理它,然后返回到客户端。我错过了什么?

这是我的Node app.js

var express = require('express');
var app = express();

app.use(function(req, res, next) {
  res.header("Access-Control-Allow-Origin", "*");
  res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
  next();
});

app.post('/calculate', function(req, res) {
    console.log('Calculation request received!');
    //console.log(req.body);
    //console.log(req.query);
    // Multiply the number by 2
    res.send("?");

});

app.listen(1337, function () {
  console.log('Listening on port 1337');
});

我的道场+ html

<html>
<body>
    <button id='calculate-button'>Calculate</button>
    <!-- load Dojo -->
    <script src="//ajax.googleapis.com/ajax/libs/dojo/1.10.4/dojo/dojo.js"
            data-dojo-config="async: true"></script>

    <script>
    require(["dojo/dom", "dojo/on", "dojo/request", "dojo/domReady!"],
        function(dom, on, request){
            on(dom.byId("calculate-button"), "click", function(evt){
                myValue = 2;
                request.post("http://localhost:1337/calculate", {value: myValue}).then(
                    function(response){
                        console.log("Result: " + response);
                    },
                    function(error){
                    }
                );
            });
        }
    );
    </script>
</body>
</html>

1 个答案:

答案 0 :(得分:1)

安装npm body-parser,以便您可以在req.body

中提取帖子数据
npm install body-parser --save
var app = express();

之后

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

添加中间件以初始化

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

安装和初始化后,发布的数据将以console.log(req.body)

的形式提供

Official Doc