首页 > 解决方案 > 忽略 http 方法和路径的 API 的缺点

问题描述

我想知道对于 api 完全不知道 HTTP 请求路径的生产服务器会有什么缺点。比如一个完全由查询参数决定,甚至完全由http body决定的api。

let server = require('http').createServer(async (req, res) => {

  let { headers, method, path, query, body } = await parseRequest(res);

  // `headers` is an Object representing headers
  // `method` is 'get', 'post', etc.
  // `path` could look like /api/v2/people
  // `query` could look like { filter: 'age>17&age<35', page: 7 }
  // `body` could be some (potentially large) http body

  // MOST apis would use all these values to determine a response...
  // let response = determineResponse(headers, method, path, query, body);

  // But THIS api completely ignores everything except for `query` and `body`
  let response = determineResponse(query, body);

  doSendResponse(res, response); // Sets response headers, etc, sends response

});

上面服务器的 API 比较奇怪。它将完全忽略路径、方法、标题和正文。虽然大多数 API 主要考虑方法和路径,但看起来像这样......

method  path                   description

GET     /api                   - Metadata about api
GET     /api/v1                - Old version of api
GET     /api/v2                - Current api
GET     /api/v2/people         - Make "people" db queries
POST    /api/v2/people         - Insert a new person into db
GET     /api/v2/vehicles       - Make "vehicle" db queries
POST    /api/v2/vehicles       - Insert a new vehicle into db
.
.
.

这个 API 只考虑 url 查询,看起来很不一样:

url query                                 description

<empty>                                   - Metadata about api
apiVersion=1                              - Old version of api
apiVersion=2                              - Current api
apiVersion=2&table=people&action=query    - Make "people" db queries
apiVersion=2&table=people&action=insert   - Add new people to db
.
.
.

实现这种 api 并确保客户端使用正确的 api 模式不一定是问题。相反,我想知道我的应用程序可能会出现哪些其他问题,因为使用这种模式编写了一个 api

标签: node.jsapiurlseo

解决方案


这确实很不寻常,但它基本上是 RPC Web api 的工作方式。

据我所知,不会有任何 SEO 问题。性能/缓存应该相同,因为完整的“路径”最终由相同的参数组成。

然而,与任何意想不到的东西(快速路由器、花哨的 http 客户端等)一起使用会很复杂。

我看到的唯一根本区别是浏览器如何将 POST 请求视为特殊请求(例如,不会仅通过链接创建),并且您的 API 将仅通过链接公开数据的删除/创建。根据您的情况,这或多或少是危险的。

我的建议是:不要那样做,坚持标准,除非你有充分的理由不这样做。


推荐阅读