2017-04-16 65 views
1

我想將數據從vue.js前端發佈到我的express/node後端。郵政似乎通過,但在後端我只是得到一個未定義的空數組。從Vue.JS發佈到Express路由器

前端:

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" 
}] 

節點服務器上console.log只是給我這個後一個POST嘗試:

{ undefined: [ '', '' ] } 

任何幫助將是巨大的。在我發佈它們之前,我可能需要用Vue數據綁定來做些什麼?我是Vue的新手,所以幾乎肯定會做錯事情。

感謝:D

+0

充滿數據的POST請求之前,前端側的'guests'陣列? – wostex

+0

是的,我已經記錄,在POST請求期間,它顯示數據在前端# –

回答

1

管理回答這個我自己。基本上由於某些原因,在Vue中使用jQuery POST會讓事情變得糟糕。我加入了"vue-resource" plugin的VUE,然後用能夠做同樣的POST:

this.$http.post('url', data);