ale*_*nco 5 javascript rest express pouchdb vue.js
我正在构建一个简单的 REST API(使用PouchDB和Vue.js)。现在,我可以创建projects几个字段:
服务器.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
})
})
Run Code Online (Sandbox Code Playgroud)
客户端.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
})
}
Run Code Online (Sandbox Code Playgroud)
如何将参数传递给 settitle和content?在 REST API 中执行此操作的常规方法是什么?
小智 6
在服务器端,您可以使用 POST 请求访问客户端发送的数据req.body。
所以你的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
})
})
Run Code Online (Sandbox Code Playgroud)
在客户端,您必须将 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
})
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
5405 次 |
| 最近记录: |