2016-02-17 37 views
3

我正在构建一个简单的REST API(使用PouchDBVue.js)。现在,我可以创造projects有几个领域:如何将参数传递给Express post HTTP方法?

server.js:

var express = require('express') 
var PouchDB = require('pouchdb') 
var app = express() 
var db = new PouchDB('vuedb') 

app.post('/projects/new', function(req, res) { 
    var data = { 
    'type': 'project', 
    'title': '', 
    'content': '', 
    'createdAt': new Date().toJSON() 
    } 
    db.post(data).then(function (result) { 
    // handle result 
    }) 
}) 

client.js:

// HTML 

<input type="text" class="form-control" v-model="title" placeholder="Enter title"> 
<input type="text" class="form-control" v-model="content" placeholder="Enter content"> 
<button class="btn btn-default" v-on:click="submit">Submit</button> 

// JS 

submit() { 
    this.$http.post('http://localhost:8080/projects/new').then(response => { 
    // handle response 
    }) 
} 

如何传递参数来设置titlecontent?在REST API中这样做的传统方式是什么?

+0

网址参数:'HTTP://本地主机:8080 /项目/新标题=外国人和内容= scream' ... Express有方法('req.params'我认为)选择这些值。 – Andy

回答

2

在服务器端,您可以使用req.body访问POST请求中客户端发送的数据。

所以你server.js文件将是这样的:

var express = require('express') 
var PouchDB = require('pouchdb') 
var app = express() 
var db = new PouchDB('vuedb') 

app.post('/projects/new', function(req, res) { 
    var data = { 
    'type': 'project', 
    'title': req.body.title, 
    'content': req.body.content, 
    'createdAt': new Date().toJSON() 
    } 
    db.post(data).then(function (result) { 
    // handle result 
    }) 
}) 

在客户端,你必须有一个对象传递您的POST请求的身体的$http.post第二个参数。 client.js应该是这样的:

// HTML 

<input type="text" class="form-control" v-model="title" placeholder="Enter title"> 
<input type="text" class="form-control" v-model="content" placeholder="Enter content"> 
<button class="btn btn-default" v-on:click="submit">Submit</button> 

// JS 

submit() { 
    this.$http.post('http://localhost:8080/projects/new', { 
    title: 'Your title', 
    content: 'The content' 
    }).then(response => { 
    // handle response 
    }) 
} 
+1

完美。谢谢!所以这是REST API的传统方式吗? – alexchenco

+1

不客气!是的,这是对POST/UPDATE/DELETE请求执行此操作的传统方式:您在请求中发送主体以提供数据。唯一不同的方法是GET(你可以在URL中使用参数,并且可以在Node中使用'req.params.myvar'来获得它 – fbouquet

+0

噢,我明白了,但是为什么不使用'req。 body' for GET too?这是不可能的?或者有缺点? – alexchenco