简体   繁体   中英

dio put operation not working in fllutter

Im trying to connect flutter web app with mongodb using restheart api. PUT operation is required for creating new collection in mongoDB. I checked request in Postman, its works fine. I can get data from already existing collection (GET, POST works fine).

Code:

Dio dio = new Dio();
  dio.interceptors.add(InterceptorsWrapper(onRequest:
   (RequestOptions options) async {
    var customHeaders = {
      'content-type': 'application/json',
      HttpHeaders.authorizationHeader: "Basic $encoded"
    };
    options.headers.addAll(customHeaders);
    return options;      
  }));  
  String url = "http://localhost:8080/toofo";
  response2 = await dio.put(url);
  print("############## ${response2.statusCode} ##########");
  print("############## ${response2.data} ##########");

Error:

 Error: DioError [DioErrorType.RESPONSE]: XMLHttpRequest error.
    at Object.throw_ [as throw] (http://localhost:52789/dart_sdk.js:4773:11)
    at dio_for_browser.DioForBrowser.new.<anonymous> (http://localhost:52789/packages/dio/src/entry/dio_for_browser.dart.lib.js:359:27)
    at Generator.next (<anonymous>)
    at onValue (http://localhost:52789/dart_sdk.js:35655:33)
    at _RootZone.runUnary (http://localhost:52789/dart_sdk.js:35540:58)
    at _FutureListener.thenAwait.handleValue (http://localhost:52789/dart_sdk.js:30956:29)
    at handleValueCallback (http://localhost:52789/dart_sdk.js:31466:49)
    at Function._propagateToListeners (http://localhost:52789/dart_sdk.js:31498:17)
    at _Future.new.[_completeWithValue] (http://localhost:52789/dart_sdk.js:31357:23)
    at async._AsyncCallbackEntry.new.callback (http://localhost:52789/dart_sdk.js:31377:35)
    at Object._microtaskLoop (http://localhost:52789/dart_sdk.js:35756:13)
    at _startMicrotaskLoop (http://localhost:52789/dart_sdk.js:35762:13)

I also tried http package in flutter, got similar error.

This is the postman's status of PUT request 201Created

XMLHttpRequest error occurs for cross origin. Use this hearder

  headers: {
  'content-type': 'application/json',
 "Access-Control-Allow-Origin": "*", // Required for CORS support to work
 "Access-Control-Allow-Credentials": true, // Required for cookies, authorization   headers with HTTPS
   "Access-Control-Allow-Headers": "Origin,Content-Type,X-Amz-Date,Authorization,X-Api-Key,X-Amz-Security-Token,locale",
  "Access-Control-Allow-Methods": "POST, OPTIONS"
 },

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM