Sunday, 16 April 2017

Posting to Express router from Vue.JS

I am trying to post data from a vue.js front end to my express/node backend. The POST seems to go through but on the backend I'm just getting an undefined empty array.

Front End:

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'
        });
    },
...

Back End:

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);
});

The guests array is populated by another function which I've omitted. It looks like this:

[{
   fullName: "john smith",
   rsvpStatus: "Not Responded"
},{
   fullName: "Mr Stack Overflow",
   rsvpStatus: "Yes"
}]

the console.log on the node server is just giving me this after a POST attempt:

{ undefined: [ '', '' ] }

Any help would be great. Maybe there's something I need do with Vue data bindings before I post them? I'm new to Vue so almost certainly doing something wrong.

Thanks :D



via Ed Shee

No comments:

Post a Comment