从Vue.JS发布Express路由器

时间:2017-04-16 20:31:15

标签: node.js http express vue.js

我正在尝试将数据从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"
}]

节点服务器上的console.log只是在POST尝试后给我这个:

{ undefined: [ '', '' ] }

任何帮助都会很棒。也许在发布之前我需要做一些Vue数据绑定吗?我是Vue的新手,所以几乎肯定做错了。

谢谢:D

1 个答案:

答案 0 :(得分:1)

管理自己回答这个问题。基本上由于某种原因在Vue中使用jQuery POST会让事情变得混乱。我为vue添加了"vue-resource" plugin,然后能够使用以下命令执行相同的POST:

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