I'm building a simple REST API (with PouchDB and Vue.js). Right now, I can create projects
with a few fields:
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
})
}
How can I pass parameters to set title
and content
? What's the conventional way of doing this in a REST API?
js POST Method. Post method facilitates you to send large amount of data because data is send in the body. Post method is secure because data is not visible in URL bar but it is not used as popularly as GET method. On the other hand GET method is more efficient and used more than POST.
The path parameter is a variable that allows the user to add a parameter in his resource point (API endpoint) whose value can be changed. Path parameters offer a unique opportunity for the user to control the representations of resources. Just create a folder and add a file for example index.
On the server side, you can access to the data sent by the client in a POST request using req.body
.
So your server.js file would be like this:
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
})
})
On the client side, you'll have to pass the body of your POST request with an object as the second parameter of $http.post
. client.js would look like this:
// 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
})
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With