Flutter JSON REST服务器搭建插件json_rest_server的使用

Flutter JSON REST服务器搭建插件 json_rest_server 的使用

简介

Json Rest Server 是一个基于 JSON 的 RESTful 服务器。它可以帮助你快速搭建一个功能完备的 RESTful 服务器,支持认证、分页和其他必要的服务。

安装

  1. 安装 Dart
    如果你已经安装了 Flutter,那么你不需要单独安装 Dart。如果没有,可以访问 Dart 官方网站 进行安装。

  2. 激活 Json Rest Server
    使用以下命令激活 json_rest_server

    dart pub global activate json_rest_server
    

配置

配置文件 config.yaml 包含了服务器的各种配置参数:

name: MyServer
port: 8080
host: 0.0.0.0
database: database.json
idType: uuid

参数说明

  • name: 服务器名称
  • port: 访问端口
  • host: 访问 IP,如果希望同时响应 IP 和 localhost,设置为 0.0.0.0
  • database: 数据库文件名
  • idType: ID 类型,可以是 uuidint

命令

更新

更新 Json Rest Server 版本:

json_rest_server upgrade

创建项目

在空文件夹中执行以下命令创建项目:

json_rest_server create

如果你想让 Json Rest Server 创建文件夹,可以使用:

json_rest_server create ./nome_pasta

启动服务器

在创建项目的文件夹中执行以下命令启动服务器:

json_rest_server run

路由

运行 Json Rest Server 后,路由将基于 database.json 文件中的数据生成。例如:

{
    "products": [
        {
            "id": 0,
            "title": "Academia do flutter"
        },
        {
            "id": 1,
            "title": "Jornada Dart"
        },
        {
            "id": 2,
            "title": "Jornada GetX"
        }
    ]
}

生成的路由

  • GET /products - 获取所有产品
  • GET /products?title=jornada - 带过滤器获取所有产品
  • GET /products?page=1&limit=10 - 分页获取所有产品
  • GET /products?page=1&limit=10&title=Jornada - 带过滤器分页获取所有产品
  • GET /products/1 - 获取单个产品
  • POST /products - 添加一个产品
  • PUT /products/1 - 编辑一个产品
  • PATCH /products/1 - 编辑一个产品
  • DELETE /products/1 - 删除一个产品

注意

  • POST, PUT, PATCH 方法需要包含 JSON 格式的请求体。

测试超时

在所有 HTTP 请求中,可以通过在请求头中添加 mock-delay 字段来测试连接超时。例如:

mock-delay:10

认证

Json Rest Server 默认支持通过 JWT 进行认证。启用认证需要在 config.yaml 中添加 auth 属性:

auth:
  jwtSecret: cwsMXDtuP447WZQ63nM4dWZ3RppyMl
  jwtExpire: 3600
  unauthorizedStatusCode: 403
  urlSkip:
    - /users:
        method: post
    - /products/{*}:
        method: get
  authFields:
    - matricula:
        type: int
    - celular:
        type: string
    - nota:
        type: double

登录

发送 POST 请求到 http://localhost:8080/auth,请求体如下:

{
    "email": "rodrigorahman@academiadoflutter.com.br",
    "password": "123"
}

如果自定义了 authFields,请求体应如下:

{
    "matricula": 102030,
    "celular": "+5535988881234",
    "nota": 8.5
}

访问受保护的路由

在请求头中添加 Authorization 字段,值为 Bearer <token>

Response response = await http.get(
  'http://localhost:8080/products',
  headers: {'authorization': "Bearer $token"},
);

刷新令牌

发送 PUT 请求到 http://localhost:8080/auth/refresh,请求体包含 refresh_token

Response response = await http.put(
  'http://localhost:8080/auth/refresh',
  headers: {'authorization': "Bearer $token"},
  body: jsonEncode({
    "refresh_token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJleHAiOjE2NjI0MjI3NTIsImlhdCI6MTY2MTgxNzk1MiwiaXNzIjoiZXlKaGJHY2lPaUpJVXpJMU5pSXNJblI1Y0NJNklrcFhWQ0o5LmV5SmxlSEFpT2pFMk5qRTRNVGM1T0RJc0ltbGhkQ0k2TVRZMk1UZ3hOemsxTWl3aWFYTnpJam9pYW5OdmJsOXlaWE4wWDNObGNuWmxjaUlzSW01aVppSTZNVFkyTVRneE56azFNaXdpYzZWaUlqb2lNU0o5LkROV0MwalVQSnc5OExWNGpnREJTTU5CbWFqQnlQYTh2RWNMSXBXSTYybVEiLCJuYmYiOjE2NjE4MTc5ODIsInN1YiI6IlJlZnJlc2hUb2tlbiJ9.2oUEvmJWAiM_jbBGtwsRB-PasgU1R1e6c5aefH98Xrk",
  }),
);

示例代码

创建项目

在空文件夹中执行以下命令创建项目:

json_rest_server create

启动服务器

进入创建的文件夹并启动服务器:

json_rest_server run

访问示例

获取所有产品

import 'package:http/http.dart' as http;

void main() async {
  final response = await http.get(Uri.parse('http://localhost:8080/products'));
  if (response.statusCode == 200) {
    print(response.body);
  } else {
    print('Request failed with status: ${response.statusCode}');
  }
}

登录

import 'package:http/http.dart' as http;
import 'dart:convert';

void main() async {
  final response = await http.post(
    Uri.parse('http://localhost:8080/auth'),
    headers: {'Content-Type': 'application/json'},
    body: jsonEncode({
      "email": "rodrigorahman@academiadoflutter.com.br",
      "password": "123"
    }),
  );
  if (response.statusCode == 200) {
    print(response.body);
  } else {
    print('Request failed with status: ${response.statusCode}');
  }
}

访问受保护的路由

import 'package:http/http.dart' as http;

void main() async {
  final token = "your_jwt_token_here";
  final response = await http.get(
    Uri.parse('http://localhost:8080/products'),
    headers: {'Authorization': 'Bearer $token'},
  );
  if (response.statusCode == 200) {
    print(response.body);
  } else {
    print('Request failed with status: ${response.statusCode}');
  }
}

刷新令牌

import 'package:http/http.dart' as http;
import 'dart:convert';

void main() async {
  final token = "your_jwt_token_here";
  final refreshToken = "your_refresh_token_here";
  final response = await http.put(
    Uri.parse('http://localhost:8080/auth/refresh'),
    headers: {'Authorization': 'Bearer $token'},
    body: jsonEncode({
      "refresh_token": refreshToken,
    }),
  );
  if (response.statusCode == 200) {
    print(response.body);
  } else {
    print('Request failed with status: ${response.statusCode}');
  }
}

以上是 json_rest_server 插件的基本使用方法和示例代码。希望这些信息对你有所帮助!


更多关于Flutter JSON REST服务器搭建插件json_rest_server的使用的实战教程也可以访问 https://www.itying.com/category-92-b0.html

1 回复

更多关于Flutter JSON REST服务器搭建插件json_rest_server的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html


在Flutter中搭建一个JSON REST服务器,可以使用json_rest_server插件。这个插件允许你在Flutter应用中轻松地启动一个本地的REST服务器,并处理JSON请求和响应。以下是一个基本的使用案例,展示如何设置和使用这个插件。

首先,你需要在你的pubspec.yaml文件中添加json_rest_server依赖:

dependencies:
  flutter:
    sdk: flutter
  json_rest_server: ^最新版本号  # 请替换为实际的最新版本号

然后,运行flutter pub get来安装依赖。

接下来,是一个简单的Flutter应用示例,它使用json_rest_server来启动一个REST服务器,并处理GET和POST请求。

import 'package:flutter/material.dart';
import 'package:json_rest_server/json_rest_server.dart';
import 'dart:convert';

void main() {
  // 启动REST服务器
  startJsonServer();

  runApp(MyApp());
}

void startJsonServer() async {
  final server = JsonRestServer(port: 8080);

  // 添加GET请求处理器
  server.get('/api/data', (req) async {
    Map<String, dynamic> responseData = {
      'message': 'Hello, World!',
      'timestamp': DateTime.now().toIso8601String(),
    };
    return JsonResponse.ok(responseData);
  });

  // 添加POST请求处理器
  server.post('/api/data', (req) async {
    Map<String, dynamic> requestData = jsonDecode(await req.readAsString()) as Map<String, dynamic>;
    Map<String, dynamic> responseData = {
      'received': requestData,
      'timestamp': DateTime.now().toIso8601String(),
    };
    return JsonResponse.ok(responseData);
  });

  // 启动服务器
  await server.start();
  print('REST server started on port 8080');
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: Text('Flutter JSON REST Server'),
        ),
        body: Center(
          child: Text('REST server is running in the background. Use tools like Postman or curl to test the endpoints.'),
        ),
      ),
    );
  }
}

在这个示例中,我们做了以下几件事:

  1. main函数中,我们首先调用了startJsonServer函数来启动REST服务器。
  2. startJsonServer函数中,我们创建了一个JsonRestServer实例,并指定了端口号8080。
  3. 使用server.get方法为/api/data路径添加了一个GET请求处理器,它返回一个包含消息和当前时间戳的JSON响应。
  4. 使用server.post方法为/api/data路径添加了一个POST请求处理器,它读取请求体中的JSON数据,并返回一个包含接收到的数据和当前时间戳的JSON响应。
  5. 启动了服务器,并在控制台中打印了一条消息,表明服务器已启动。
  6. 创建了一个简单的Flutter应用,显示一个消息,告知用户REST服务器正在后台运行。

你可以使用工具如Postman或curl来测试这些端点。例如,你可以发送一个GET请求到http://localhost:8080/api/data,或者发送一个POST请求到相同的URL,并在请求体中包含JSON数据。

回到顶部