首页 文章

从Vue.JS发布到Express路由器

提问于
浏览
1

我试图将数据从vue.js前端发布到我的快递/节点后端 . 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"
}]

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

{ undefined: [ '', '' ] }

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

感谢:D

1 回答

  • 1

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

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

相关问题