dio put operation not working in fllutter

1.5k Views Asked by At

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

1

There are 1 best solutions below

0
Samu Chakraborty On

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"
 },