0

I have an ASP.Net Core web api that accepts bearer token (jwt) and I send this token in my Flutter with Android emulator without any problem with this code :

final response = await get(url, headers: {
      'Content-Type': 'application/json',
      'Accept': 'application/json',
      'Authorization': 'Bearer $token',
    });

But when I run this in Chrome browser the api response is : 405 Method Not Allowed .

What's the problem ?

UPDATE :

According to @anirudh comment I have enabled CROS in my web Api and problem have changed . Now the response is : 204 No Content

mm sh
  • 192
  • 3
  • 18

3 Answers3

5

use http plugin

And do http.get and not just get

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

final response = await http.get(url, headers: {
      'Content-Type': 'application/json',
      'Accept': 'application/json',
      'Authorization': 'Bearer $token',
    });
anirudh
  • 1,436
  • 5
  • 18
  • @mmsh 405 occurs due to wrong request as far as I know. Pls try changing `get` to `post`. Also recheck your curl from [this](https://curl.trillworks.com/#dart) – anirudh May 15 '21 at 06:46
  • Error: XMLHttpRequest error . if the problem is get or post why I don't have any problem in android with exactly same code ? – mm sh May 15 '21 at 06:49
  • @mmsh Check [this answer](https://stackoverflow.com/questions/60191683/xmlhttprequest-error-in-flutter-web-enabling-cors-aws-api-gateway) – anirudh May 15 '21 at 06:50
  • @mmsh for 204 check [this](https://stackoverflow.com/questions/12807753/http-get-with-204-no-content-is-that-normal) – anirudh May 15 '21 at 11:53
1

Thanks to @anirudh I solved my problem

First defining a variable :

readonly string MyAllowSpecificOrigins = "_myAllowSpecificOrigins";

Then write these codes in my api in ConfigureServices :

services.AddCors(options =>
    {
        options.AddPolicy(name: MyAllowSpecificOrigins,
            builder =>
                {
                    builder.WithOrigins("http://localhost") //Or my flutter web host
                        .AllowAnyMethod()
                        .AllowAnyHeader()
                        .SetIsOriginAllowed((host) => true);
                });
    });

and this line in Configure :

app.UseCors(MyAllowSpecificOrigins);
mm sh
  • 192
  • 3
  • 18
0
String token = await Candidate().getToken();
final response = await http.get(url, headers: {
  'Content-Type': 'application/json',
  'Accept': 'application/json',
  'Authorization': 'Bearer $token',
});
print('Token : ${token}');
print(response);