简体   繁体   English

将请求从Backbone客户端发布到NodeJS服务

[英]Post request from Backbone client to NodeJS service

Somehow I am not able to send data from Backbone model to NodeJS service. 我无法以某种方式将数据从Backbone模型发送到NodeJS服务。
Backbone Model 骨干模型

var Money = Backbone.Model.extend({
    url: 'http://localhost:3000/sendCoins',
    defaults: {
        fromAddress: "",
        toAddress: "",
        amount: ""
    },
    transferMoney: function(req, resp) {
        //get field values
        console.log(req.fromAddress); //prints fine
        this.save();
    }
});

var transferMoney = new Money();

Node JS service Node JS服务

var app = express();
    app.listen(3000);
    app.use(express.json());

app.use(function (req, res, next) {

    // Website you wish to allow to connect
    res.setHeader('Access-Control-Allow-Origin', '*');

    // Request methods you wish to allow
    res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, PATCH, DELETE');

    // Request headers you wish to allow
    res.setHeader('Access-Control-Allow-Headers', 'X-Requested-With,content-type');

    // Set to true if you need the website to include cookies in the requests sent
    // to the API (e.g. in case you use sessions)
    res.setHeader('Access-Control-Allow-Credentials', true);

    // Pass to next layer of middleware
    next();
});


app.post('/sendCoins', function(req, res) {
    console.log(req.body.toAddress);
    console.log(JSON.stringify(req.body));
    console.log(req.body.amount);
});

When I post the request from backbone view console.log(JSON.stringify(req.body)); 当我从主干视图发布请求时console.log(JSON.stringify(req.body)); prints {"fromAddress":"","toAddress":"","amount":""} . 打印{"fromAddress":"","toAddress":"","amount":""}

As mentionned by M Omary, you need to use the body parser in order to have access to req.body . 如M Omary所述,您需要使用主体解析器才能访问req.body Add the following code above app.post to see if it works: app.post上方添加以下代码以查看其是否有效:

app.use(express.bodyParser());

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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