node.js - 从 Vue.JS 发布到 Express 路由器

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

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/

相关文章:

.net - 限制 WebClient DownloadFile 最大文件大小

javascript - header 中包含文件数据的发布请求。好的做法吗?

angularjs - Angular JS。预检响应中的 Access-Control-Allow-Headers 不允许请求 header 字段 Access-Control-Allow-Origin

node.js - 如何检查正在使用的 Express.js 中间件集?

javascript - server.js 文件外部的快速路由

xml - 用node.js解析大xml 500M

node.js - Mongo 仅以 ISO_8601 格式存储日期,而不是 unix

node.js - 如何修复工作服的 `405 Not Allowed` 错误

node.js - 将多个回调函数传递给 Express 路由

testing - 使用 Node.js TCP 服务器进行测试驱动开发?