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

Posted

技术标签:

【中文标题】如何将参数传递给 Express post HTTP 方法?【英文标题】:How do you pass parameters to an Express post HTTP method? 【发布时间】:2016-05-29 05:42:19 【问题描述】:

我正在构建一个简单的 REST API(使用 PouchDB 和 Vue.js)。现在,我可以用几个字段创建projects

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 中执行此操作的传统方法是什么?

【问题讨论】:

URL 参数:http://localhost:8080/projects/new?title=Alien&amp;content=scream... Express 有方法(我认为是req.params)来挑选这些值。 【参考方案1】:

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

【讨论】:

完美。谢谢!那么这是 REST API 的传统方式吗? 不客气!是的,这是对 POST / UPDATE / DELETE 请求执行此操作的传统方式:您在请求中发送一个主体以提供数据。唯一不同的 HTTP 方法是 GET(您将在 URL 中包含参数,并在 Node 中使用 req.params.myvar 获取它。 哦,我明白了。但是为什么不将req.body 也用于 GET 呢?这是不可能的?还是有缺点? 这可能是可能的,但这不是 HTTP 协议的设计方式。根据定义,GET 请求完全由 URI 定义,不应使用请求正文(有关详细信息,请参阅***.com/questions/978061/http-get-with-request-body)。不确定这个猜测,但我会说 URI 本身应该足以识别唯一 GET 请求的一个潜在原因是例如用于缓存目的。

以上是关于如何将参数传递给 Express post HTTP 方法?的主要内容,如果未能解决你的问题,请参考以下文章