我正在构建一个简单的REST API(使用PouchDB和Vue.js).现在,我可以用几个字段创建项目:
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
})
}
如何传递参数来设置标题和内容?在REST API中执行此操作的常规方法是什么?
解决方法:
在服务器端,您可以使用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
})
})
在客户端,您必须使用对象作为$http.post的第二个参数传递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
})
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。