javascript - 如何将参数传递给 Express post HTTP 方法?

标签 javascript rest express vue.js pouchdb

我正在构建一个简单的 REST API(使用 PouchDBVue.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
  })
})

客户端.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 中执行此操作的常规方法是什么?

最佳答案

在服务器端,您可以使用 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
  })
}

关于javascript - 如何将参数传递给 Express post HTTP 方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35458065/

相关文章:

java - JQuery ajax GET 请求,响应状态为 200 OK 时未触发成功

rest - REST MarkLogic 中的自定义搜索结果

mongodb - Mongoose : don't insert if element already stored

javascript - jQuery 根据单选字段更新复选框值?

javascript - 如何通过在 webpack 4 中设置 eslint 来解决导入/未解决问题

javascript - 是否可以有包含日期​​的从 1 到 52 周的下拉列表?默认为本周

rest - 需要帮助在 tomcat 上设置 CORS

node.js - 更好的布局表达,将app和io对象传递给路由

node.js - Expressjs 原始正文

JavaScript 代码未加载(仅第一次)