不知何故,我无法将Backbone模型的数据发送到NodeJS服务。
骨干模型
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();
节点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);
});
当我从骨干视图console.log(JSON.stringify(req.body));
发布请求时,打印{"fromAddress":"","toAddress":"","amount":""}
。
答案 0 :(得分:0)
正如M Omary所提到的,您需要使用正文解析器才能访问req.body
。在app.post
上方添加以下代码,看它是否有效:
app.use(express.bodyParser());