我们的第一个Feathers应用程序¶
现在我们 设置 我们可以创建我们的第一个Feathers应用程序.它可以在NodeJS和浏览器中使用.首先, 让我们为我们运行的所有示例创建一个新文件夹:
mkdir feathers-basics
cd feathers-basics
由于任何Feathers应用程序都是Node应用程序, 我们可以使用 npm 创建一个默认的 package.json :
npm init --yes
安装Feathers¶
通过 npm 安装 @feathersjs/feathers 包,可以像任何其他Node模块一样安装Feathers. 相同的包也可以与Browserify或Webpack和React Native等模块加载器一起使用.
npm install @feathersjs/feathers --save
注解
所有Feathers核心模块都在 @feathersjs npm 命名空间中.
你的第一个应用¶
任何Feathers应用程序的基础是 应用, 可以像这样创建:
const feathers = require('@feathersjs/feathers');
const app = feathers();
这个应用程序对象有几种方法, 最重要的是它允许我们注册服务.我们将在下一章中了解有关服务的更多信息, 现在让我们通过创建一个 app.js 文件(在当前文件夹中)注册并使用一个只有 get 方法的简单服务, 如下所示:
const feathers = require('@feathersjs/feathers');
const app = feathers();
// Register a simple todo service that returns the name and some text
app.use('todos', {
async get(name) {
// Return an object in the form of { name, text }
return {
name,
text: `You have to do ${name}`
};
}
});
// A function that gets and logs a todo from the service
async function getTodo(name) {
// Get the service we registered above
const service = app.service('todos');
// Call the `get` method with a name
const todo = await service.get(name);
// Log the todo we got back
console.log(todo);
}
getTodo('dishes');
我们可以运行它
node app.js
应该看到
{ name: 'dishes', text: 'You have to do dishes' }
小技巧
有关Feathers应用程序对象的更多信息, 请参阅 应用.
在浏览器中¶
我们上面创建的Feathers应用程序也可以在浏览器中运行.在这里加载Feathers的最简单方法是通过一个指向CDN版本Feathers的 <script> 标签.加载它将使 feathers 全局变量可用.
我们将浏览器文件放入一个新文件夹中
mkdir public
我们还需要使用网络服务器托管该文件夹.这可以通过任何像Apache这样的网络服务器或 http-server模块 来完成, 我们可以安装和托管 public/ 文件夹像这样:
npm install http-server -g
http-server public/
注解
您必须使该服务器在基础指南中的所有浏览器示例中运行才能运行.
在 public/ 文件夹中, 我们添加两个文件, 一个将加载Feathers的 index.html:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Feathers Basics</title>
</head>
<body>
<h1>Welcome to Feathers</h1>
<p>Open up the console in your browser.</p>
<script type="text/javascript" src="//unpkg.com/@feathersjs/client@^3.0.0/dist/feathers.js"></script>
<script src="client.js"></script>
</body>
</html>
并且 client.js 看起来像这样:
const app = feathers();
// Register a simple todo service that return the name and a text
app.use('todos', {
async get(name) {
// Return an object in the form of { name, text }
return {
name,
text: `You have to do ${name}`
};
}
});
// A function that gets and logs a todo from the service
async function logTodo(name) {
// Get the service we registered above
const service = app.service('todos');
// Call the `get` method with a name
const todo = await service.get(name);
// Log the todo we got back
console.log(todo);
}
logTodo('dishes');
您可能会注意到它与Node的 app.js 几乎相同, 只是缺少 feathers 导入(因为它已经可用作全局变量).
如果您现在转到 localhost:8080 并打开控制台,您也会看到记录的结果.
注解
您还可以使用 Webpack 或 Browserify 等模块加载程序加载Feathers. 有关更多信息, 请参阅 Feathers 客户端.