创建 REST API 而不使用任何后端

问题描述 投票:0回答:2

如何在不使用任何后端技术(例如node、express)的情况下创建rest api?即:是否可以仅使用客户端框架(例如react、vue)创建api而不涉及服务器端?

我想创建一个非常简单的 REST API,我可以将其托管在 github 页面或 gitlab 页面上。

我想要一个可以通过我自己的域访问的实时休息 API,例如 http://username.github.io,而不是您可以使用 json-serverMy JSON Server 创建的假 API - 并且能够执行以下操作。

这里是 api 应该做什么的描述。

/quotes.txt - 读取quotes.txt文件的内容并显示它

/quotes.json - 读取quotes.txt文件的内容并将其转换 转为json格式

/random.txt - 读取quotes.txt文件的内容并显示 txt 格式的随机引用

/random.json - 读取quotes.txt文件的内容并显示 json 格式的随机引用

API 的输出

/quotes.txt

To be or not to be that is the question - Author Unknown
All your dreams can come true if you have the courage to pursue them - Walt Disney
Stand up for what you believe in even if you are standing alone - 

/quotes.json

[
  {
    "quote": "To be or not to be that is the question",
    "author": "Author Unknown"
  },
  {
    "quote": "All your dreams can come true if you have the courage to pursue them",
    "author": "Walt Disney"
  },
  {
    "quote": "Stand up for what you believe in even if you are standing alone",
    "author": ""
  }
]

/随机.txt

All your dreams can come true if you have the courage to pursue them - Walt Disney

/随机.json

  {
    "quote": "All your dreams can come true if you have the courage to pursue them",
    "author": "Walt Disney"
  }
json rest api backend static-site
2个回答
1
投票

您可以使用 json-server 来提供 JSON 文件。它支持表达 RESTful 请求的“规范”方式。该工具可以在开发机或内网服务器上使用。这是一篇关于如何设置的博客文章

My JSON Server 是一项在 Internet 环境中为您执行完全相同的操作的服务。还有具有类似功能的竞争服务,例如myjson.com。我相信如果您上网搜索,您会找到更多。


附注我确信您需要做一些按摩才能真正翻译

.txt
->
.json
。我从未见过针对
.txt
文件而不是
.json
文件的服务。

呃。我真的很喜欢使答案无效的问题编辑。


0
投票

是的,您可以在Service Worker的帮助下在浏览器中创建一个API,而无需任何服务器,它可以在浏览器中创建对HTTP请求的纯HTTP响应

我创建了一个名为 Wayne 的库,它的 API 几乎与 Express.js 中的相同。

要在 Wayne 中创建 API,您需要注册 Service Worker,并在 Service Worker 中使用如下代码:

importScripts('https://cdn.jsdelivr.net/npm/@jcubic/wayne/index.umd.min.js');

const app = new wayne.Wayne();

app.get('/api/login', (req, res) => {
   res.json({ok: true});
});

此代码将在 /api/login 中创建“假”API,该 API 将返回静态 JSON:

"{ok: true}"

因此,您可以仅使用 JavaScript 创建全栈应用程序并将其托管在 GitHub 页面或 Netlify 上。

有关其他功能的更多信息,请参阅 GitHub 上的自述文件

© www.soinside.com 2019 - 2024. All rights reserved.