我正在尝试将数据从 vue.js 前端发布到我的express/node 后端。 POST 似乎已经完成,但在后端我只是得到一个未定义的空数组。
前端:main.js
var app = new Vue({
el: '#app',
data: {
guests: [],
code: '',
showGuests: true
},
methods: {
saveGuests: function() {
$.ajax({
type: "POST",
url: '/api/rsvp/' + this.code,
data: this.guests,
success: function() {
this.showGuests = false;
// do more stuff to handle submission
},
dataType: 'json'
});
},
...
后端:
app.js
//body parser
var bodyParser = require('body-parser')
//express
var express = require('express');
// cfenv provides access to your Cloud Foundry environment
// for more info, see: https://www.npmjs.com/package/cfenv
var cfenv = require('cfenv');
// create a new express server
var app = express();
var rsvp = cloudant.db.use('rsvp');
// get the app environment from Cloud Foundry
var appEnv = cfenv.getAppEnv();
// parse application/x-www-form-urlencoded
app.use(bodyParser.urlencoded({
extended: false
}))
// parse application/json
app.use(bodyParser.json())
// serve the files out of ./public as our main files
app.use(express.static(__dirname + '/public'));
//endpoint to post rsvp details
app.post('/api/rsvp/:code', function(req, res) {
console.log(req.body);
res.send('POST request received successfully')
});
// start server on the specified port and binding host
app.listen(appEnv.port, '0.0.0.0', function() {
// print a message when the server starts listening
console.log("server starting on " + appEnv.url);
});
guests
数组由我省略的另一个函数填充。它看起来像这样:
[{
fullName: "john smith",
rsvpStatus: "Not Responded"
},{
fullName: "Mr Stack Overflow",
rsvpStatus: "Yes"
}]
Node 服务器上的 console.log
在 POST 尝试后只是给我这个:
{ undefined: [ '', '' ] }
任何帮助都会很棒。也许在发布 Vue 数据绑定(bind)之前我需要做一些事情?我是 Vue 新手,所以几乎肯定做错了什么。
谢谢:D
最佳答案
我自己设法回答了这个问题。基本上由于某种原因在 Vue 中使用 jQuery POST 会把事情搞砸。我添加了"vue-resource" plugin对于 vue,然后可以使用以下命令执行相同的 POST:
this.$http.post('url', data);
关于node.js - 从 Vue.JS 发布到 Express 路由器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43441837/