Solution: Proxy + CORS

In order to save you time, let’s cut to the chase and go straight to the code

1. First we need to introduce shelf_Proxy in pubspec.yaml:

Dev_dependencies: shelf_proxy: ^ 1.0.0Copy the code

2. Create proxy.dart in the lib directory

import 'dart:io'; import 'package:shelf/shelf_io.dart' as shelf_io; import 'package:shelf_proxy/shelf_proxy.dart'; final String target = 'http://api.test.com/'; // API Address Final String imgTarget = 'https://img.test.com/'; Void configServer(HttpServer server) { Allows all of the server. DefaultResponseHeaders. Add (' Access - Control - Allow - Origin ', '*'); server.defaultResponseHeaders.add('Access-Control-Allow-Credentials', true); server.defaultResponseHeaders.add('Access-Control-Allow-Methods', '*'); server.defaultResponseHeaders.add('Access-Control-Allow-Headers', '*'); server.defaultResponseHeaders.add('Access-Control-Max-Age', '3600'); } void main() async { var reqHandle = proxyHandler(target); var imgHandle = proxyHandler(imgTarget); Var server = await shelf_io.serve(reqHandle, 'localhost', 4500); var imgServer = await shelf_io.serve(imgHandle, 'localhost', 4501); configServer(server); configServer(imgServer); print('Api Serving at http://${server.address.host}:${server.port}'); print('Img Serving at http://${imgServer.address.host}:${imgServer.port}'); }Copy the code
  1. Dart proxy.dart Run the dart proxy server

  2. Set the BaseUrl of the request to http://localhost:4500 and the BaseUrl of the image to http://localhost:4501

  3. Add
    to the tag in web/index.html to prevent image 403

  4. test

ajax.dart

import 'package:dio/dio.dart'; import 'request_interceptor.dart'; import 'log_interceptor.dart'; class Ajax { final String baseUrl = ''; late Dio _dio; Ajax._init() { init(); } static final Ajax _ajax = Ajax._init(); factory Ajax() { return _ajax; } void init({bool debug = false}) async { var _options = BaseOptions( baseUrl: debug ? 'http://localhost:4500' : 'https://api.test.com', contentType: Headers.formUrlEncodedContentType, receiveTimeout: 10 * 1000, connectTimeout: 10 * 1000, ); _dio = Dio(_options); _dio.interceptors.add(RequestInterceptor()); _dio.interceptors.add(MyLogInterceptor()); } Future<Response<T>> send<T>( String path, { String method = 'GET', data, Map<String, dynamic>? queryParameters, CancelToken? cancelToken, Options? options, ProgressCallback? onSendProgress, ProgressCallback? onReceiveProgress, }) { return _dio.request( path, options: Options(method: method), queryParameters: queryParameters, data: data, onSendProgress: onSendProgress, onReceiveProgress: onReceiveProgress, cancelToken: cancelToken, ); }}Copy the code

main.dart

void main() {
  Ajax().init(debug: true);
  
  Ajax().send('/api/test', method: 'POST', data: data)
  .then((res) {})
  .catch((e) {})
  
  runApp(MyApp());
}


Copy the code