2016-02-17 39 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