ERR_CONNECTION_REFUSED got by fetch data with ReactJS && ASP.NET - asp.net

Hi I am working on a class group project and I am responsible for the front-end part. I am a rookie in front-end so I may have made stupid mistakes.
After I got codes in back-end from my partner:
[ApiController]
public class AccountController : ControllerBase
{
public IDBManager_Users _usersManager;
public AccountController(IDBManager_Users usersManager)
{
_usersManager = usersManager;
}
[HttpPost]
[Route("Account/Create")]
public bool CreateUser(User user)
{
bool created = _usersManager.CreateUser(user);
return created;
}
And I put a fetching data request in React to create a user:
register= e => {
e.preventDefault();
fetch(`http://localhost:5001/Account/Create`, {
method: "post",
headers: {
"Content-Type": "application/json"
},
body: JSON.stringify({
email: this.state.email,
password: this.state.password,
userRole: this.state.userRole,
country: this.state.country,
place: this.state.place,
city: this.state.city
})
})
.then((response) => {
if(response){
this.props.history.push('/login')
}
else{
alert('Please Register with Correct Info!');
}
})
.catch(err => console.log(err));
};
I think all other parts go well and I can get my request payload from Chrome like:
{"email":"abc#gmail.com","password":"abc","userRole":"1","country":"United States","place":"NY","city":"whatever"}
but fail with:
POST http://localhost:5001/Account/Create net::ERR_CONNECTION_REFUSED
I do not know what kind of stupid I have made but I really struggled into it.
Waiting for reponse :)
Edit1: If you want to have a look of startup.cs, I have attach it here:
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.Add(new ServiceDescriptor(typeof(SqlManager), new SqlManager(Configuration.GetConnectionString("DefaultConnection"))));
services.AddControllersWithViews();
services.AddCors(options =>
{
options.AddPolicy("AllowAllHeaders",
builder =>
{
builder.AllowAnyOrigin()
.AllowAnyHeader()
.AllowAnyMethod();
});
});
// In production, the React files will be served from this directory
services.AddSpaStaticFiles(configuration =>
{
configuration.RootPath = "ClientApp/build";
});
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseExceptionHandler("/Error");
// The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseSpaStaticFiles();
app.UseRouting();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllerRoute(
name: "default",
pattern: "{controller}/{action=Index}/{id?}");
});
app.UseCors("AllowAllHeaders");
app.UseSpa(spa =>
{
spa.Options.SourcePath = "ClientApp";
if (env.IsDevelopment())
{
spa.UseReactDevelopmentServer(npmScript: "start");
}
});
}
}

You need to change your method signature to map the JSON from the body of the request to the actual DTO object using the FromBody annotation:
public bool CreateUser([FromBody] User user)
Please note that since you didn't provided the code from the Startup.cs I have no idea if something else is missing there in regards of the routing and authorization.
Ref: https://learn.microsoft.com/en-us/aspnet/core/mvc/models/model-binding?view=aspnetcore-3.1#frombody-attribute

Related

I set any CORS setting but doesn't work in my ASP.NET Core 5 Web API

I enable all of the enable CORS settings, but some of these methods of request don't still work like Delete, Put.
This is my code
public void ConfigureServices(IServiceCollection services)
{
var appSettings = Configuration.GetSection("ApplicationSettings");
services.Configure<ApplicationSettingsModel>(Configuration.GetSection("ApplicationSettings"));
services.AddOptions();
services.AddControllersWithViews(options => options.UseGeneralRoutePrefix(appSettings.GetValue<string>("apiRoutePrefix") ?? ""));
services.AddMvc(o => { o.UseGeneralRoutePrefix("api/v{version:apiVersion}"); });
services.AddApiVersioning(config =>
{
config.DefaultApiVersion = new ApiVersion(1, 0);
config.AssumeDefaultVersionWhenUnspecified = true;
config.ReportApiVersions = true;
});
services.AddOurAuthentication(Configuration);
services.AddControllers(c => c.Conventions.Add(new ApiExplorerGroupPerVersionConvention()))
.AddNewtonsoftJson(options =>
{
options.SerializerSettings.ContractResolver = new DefaultContractResolver
{
NamingStrategy = new CamelCaseNamingStrategy()
};
});
services.AddCors(app =>
{
app.AddPolicy("allowAll", a => a.AllowAnyOrigin().AllowAnyHeader().AllowAnyMethod().SetIsOriginAllowedToAllowWildcardSubdomains());
});
if (_enableSwagger)
services.AddOurSwagger();
}
public void Configure(IApplicationBuilder app)
{
app.UseDeveloperExceptionPage();
SwaggerMiddleware(app);
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseCors("allowAll");
app.UseApiResponseAndExceptionWrapper();
app.UseRouting();
app.UseAuthentication();
app.UseAuthorization();
app.UseEndpoints(builder => builder.MapControllers());
}
How can I solve this problem?
You have to change the place of Cors code in your startup. Put this code to the top of ConfigureServices
public void ConfigureServices(IServiceCollection services)
{
services.AddCors(o => o.AddPolicy("AllowAnyOrigins", builder =>
{
builder.AllowAnyOrigin()
.AllowAnyMethod()
.AllowAnyHeader();
}));
...........
}
app.UseCors should be placed between app.UseRouting() and app.UseAuthorization()
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
.....
app.UseRouting();
app.UseCors("AllowAnyOrigins");
app.UseAuthentication();
app.UseAuthorization();
....
}
I resolve this.
I change my code to below:
public void ConfigureServices(IServiceCollection services)
{
var appSettings = Configuration.GetSection("ApplicationSettings");
services.Configure<ApplicationSettingsModel>(Configuration.GetSection("ApplicationSettings"));
services.AddOptions();
services.AddControllersWithViews(options => options.UseGeneralRoutePrefix(appSettings.GetValue<string>("apiRoutePrefix") ?? ""));
services.AddMvc(o => { o.UseGeneralRoutePrefix("api/v{version:apiVersion}"); });
services.AddApiVersioning(config =>
{
config.DefaultApiVersion = new ApiVersion(1, 0);
config.AssumeDefaultVersionWhenUnspecified = true;
config.ReportApiVersions = true;
});
services.AddOurAuthentication(Configuration);
services.AddControllers(c => c.Conventions.Add(new ApiExplorerGroupPerVersionConvention()))
.AddNewtonsoftJson(options =>
{
options.SerializerSettings.ContractResolver = new DefaultContractResolver
{
NamingStrategy = new CamelCaseNamingStrategy()
};
});
services.AddCors(options =>
{
options.AddPolicy("allowAll",
builder => builder
.AllowAnyMethod()
.AllowAnyHeader()
.SetIsOriginAllowed(s => true)
.SetPreflightMaxAge(TimeSpan.FromMinutes(9))
.AllowCredentials()
.Build());
});
if (_enableSwagger)
services.AddOurSwagger();
}
public void Configure(IApplicationBuilder app)
{
app.UseDeveloperExceptionPage();
SwaggerMiddleware(app);
// app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
app.UseAuthentication();
app.UseAuthorization();
app.UseCors("allowAll");
app.UseCorsMiddleware();
// app.UseApiResponseAndExceptionWrapper();
app.UseEndpoints(builder => builder.MapControllers());
}
and this code:
public class CorsMiddleware
{
private readonly RequestDelegate Next;
public CorsMiddleware(RequestDelegate next)
{
Next = next;
}
public Task Invoke(HttpContext context)
{
return BeginInvoke(context);
}
private Task BeginInvoke(HttpContext context)
{
context.Response.Headers.Add("Access-Control-Allow-Credentials", new[] { "true" });
context.Response.Headers.Add("Access-Control-Allow-Headers", new[] { "Origin, X-Requested-With, Content-Type, Accept, Athorization, ActualUserOrImpersonatedUserSamAccount, IsImpersonatedUser" });
context.Response.Headers.Add("Access-Control-Allow-Methods", new[] { "GET, POST, PUT, DELETE, OPTIONS" });
if (context.Request.Method == HttpMethod.Options.Method)
{
context.Response.StatusCode = (int)HttpStatusCode.OK;
return context.Response.WriteAsync("OK");
}
return Next.Invoke(context);
}
}
// Extension method used to add the middleware to the HTTP request pipeline.
public static class CorsMiddlewareExtensions
{
public static IApplicationBuilder UseCorsMiddleware(this IApplicationBuilder builder)
{
return builder.UseMiddleware<CorsMiddleware>();
}
}
Edited from comment suggestion, removed AllowCredentials I noticed OP didn't have that in his code.
Try this, instead of creating a policy, what if you did this:
app.UseCors(x => x
.AllowAnyMethod()
.AllowAnyHeader()
.SetIsOriginAllowed(origin => true)); // allow any origin
If this works, it's because you were creating a policy and maybe the policy is not applying. But the above should just work without a policy.
You also mention that only some verbs don't work - it's possible that a cors error is masking a 500 exception, the way to test that is, with a 500 (or other) exception, your code will actually get hit, so you can test that with a breakpoint and if your breakpoint gets hit, it's not CORS even though the browser is saying that.
But most likely you were creating a policy, and not applying the policy to the things that aren't working. THe code above is global.

SignalR authentication error when using endpoints.MapBlazorHub().RequireAuthorization()

I have a Blazor server side app that uses authentication. I tried Azure SignalR as suggested by Visual Studio but after that when I am not authenticated I get a blank page instead of the typical not authorized webpage.
If I check the browser debug console, the following message appears:
"Error: Failed to complete negotiation with the server: Error: Unauthorized"
It looks this message is thrown by signalR.
If I change the line endpoints.MapBlazorHub().RequireAuthorization(); to endpoints.MapBlazorHub() in the startup.cs file, it runs as expected.
Any idea on how to fix this?
I tried rolling back the changes made by VS, but it still doesn't work as before.
Thank you
Edit 1: This is the app.cs code for your review:
<CascadingAuthenticationState>
<Router AppAssembly="#typeof(Program).Assembly">
<Found Context="routeData">
<AuthorizeRouteView RouteData="#routeData" DefaultLayout="#typeof(MainLayout)">
<NotAuthorized>
<h1>Restricted Access</h1>
</NotAuthorized>
</AuthorizeRouteView>
</Found>
<NotFound>
<LayoutView Layout="#typeof(MainLayout)">
<p>Page not found</p>
</LayoutView>
</NotFound>
</Router>
</CascadingAuthenticationState>
Edit 2:
This is the startup class
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
// For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940
public void ConfigureServices(IServiceCollection services)
{
services.AddDbContext<IdentityBDContext>(options =>
options.UseSqlServer(
Configuration.GetConnectionString("IdentityBD"),
providerOptions => providerOptions.EnableRetryOnFailure()));
services.AddIdentity<CustomUser, IdentityRole>(options =>
{
options.User.RequireUniqueEmail = true;
options.SignIn.RequireConfirmedEmail = true; //prevents registered users from logging in until their email is confirmed.
}).AddRoles<IdentityRole>()
.AddEntityFrameworkStores<IdentityBDContext>()
.AddDefaultTokenProviders()
.AddUserManager<ERPUserManager>()
.AddSignInManager<ERPSignInManager>();
services.AddAuthorization(options =>
{
options.AddPolicy(SD.Admin, policy => policy.RequireRole(SD.Admin));
options.AddPolicy(SD.POS, policy => policy.RequireRole(SD.POS, SD.Admin));
options.AddPolicy(SD.AllowedTenant, policy => policy.Requirements.Add(new AllowedTenantRequirement(21)));
options.AddPolicy(SD.SysAdmin, policy => policy.RequireRole(SD.SysAdmin));
});
services.AddRazorPages(options =>
{
options.Conventions.AuthorizeAreaFolder("Identity", "/Account/Manage");
});
services.AddServerSideBlazor();
//services.AddSignalR().AddAzureSignalR();
services.AddScoped<AuthenticationStateProvider, RevalidatingIdentityAuthenticationStateProvider<CustomUser>>();
services.AddTransient<ConfigService>();
services.AddTransient<IdentityService>();
services.AddTransient<TenantService>();
services.AddHostedService<TimerUpdate>();
services.AddScoped<IAuthorizationHandler, AllowedTenantHandler>();
//Delete in production
services.AddServerSideBlazor().AddCircuitOptions(options => { options.DetailedErrors = true; });
services.AddScoped<ITenantProvider, WebTenantProvider>();
services.AddDbContext<ERPContext>(options => options
//.UseLoggerFactory(LoggerFactory.Create(builder => builder.AddConsole()))
.UseSqlServer(
Configuration.GetConnectionString("ERPDB")));
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
using (var serviceScope = app.ApplicationServices.GetService<IServiceScopeFactory>().CreateScope())
{
var context = serviceScope.ServiceProvider.GetRequiredService<IdentityBDContext>();
context.Database.Migrate();
}
// Workaround for https://github.com/aspnet/AspNetCore/issues/13470
app.Use((context, next) =>
{
context.Features.Get<IHttpMaxRequestBodySizeFeature>().MaxRequestBodySize = null;
return next.Invoke();
});
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
app.UseDatabaseErrorPage();
}
else
{
app.UseExceptionHandler("/Error");
// The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
app.UseAuthentication();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
endpoints.MapBlazorHub().RequireAuthorization();
endpoints.MapControllerRoute("mvc", "{controller}/{action}");
endpoints.MapFallbackToPage("/_Host");
});
}
}

authentication by [Authorize(Roles = "xxx")] in a razor pages model

I am using [Authorize(Roles = "xxx")] in my Asp.Net Core Razor Pages application. It works fine but after some minutes (maybe 5) when I click Edit or Create button in my Crud, it sign out. How may I fix this? I guess the role is alive maybe just 5 minutes(a default time), but I don't know how to remove or change it.
Here is my StartUp class:
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.Configure<CookiePolicyOptions>(options =>
{
options.CheckConsentNeeded = context => true;
options.MinimumSameSitePolicy = SameSiteMode.None;
});
services.AddDbContext<ApplicationDbContext>(options =>
options.UseSqlServer(
Configuration.GetConnectionString("DefaultConnection")));
services.AddDatabaseDeveloperPageExceptionFilter();
services.AddIdentity<IdentityUser, IdentityRole>()
.AddDefaultTokenProviders()
.AddEntityFrameworkStores<ApplicationDbContext>();
services.AddControllersWithViews();
services.AddRazorPages().AddRazorRuntimeCompilation();
services.AddScoped<PagingParameter, PagingParameter>();
services.AddTransient<IEmailSender, EmailSender>();
services.AddReCaptcha(Configuration.GetSection("ReCaptcha"));
services.AddLocalization();
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
app.UseMigrationsEndPoint();
}
else
{
app.UseExceptionHandler("/Error");
// The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
app.UseHsts();
}
{
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
app.UseAuthentication();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}");
endpoints.MapRazorPages();
});
}
}
}
Try to change the cookie ExpireTimeSpan:
services.ConfigureApplicationCookie(options =>
{
options.ExpireTimeSpan = TimeSpan.FromMinutes(30);
});
You can refer to the doc for more details.
You got 2 options. As #mj1313 mentioned you can either use:
services.ConfigureApplicationCookie(options =>
{
options.SlidingExpiration = true; // instruct the handler to re-issue a new cookie with a new expiration time any time it processes a request which is more than halfway through the expiration window
options.ExpireTimeSpan = TimeSpan.FromMinutes(30);
});
and the other one is to pass expiration time in AuthenticationProperties while signing in:
var props = new AuthenticationProperties {
IsPersistent = true,
ExpiresUtc = DateTimeOffset.UtcNow.Add(//put expiration time here)
};

Migration from .net core 2.2 to 3.1 - api 404 error

I develop a SPA with .net core at server side (and Angular for the clients).
After migration from .net core 2.2 to 3.1 the api systematically responds with error 404. I have no clue where to get into the problem.
Here is the content of the Startup.cs. Thanks a lot for any hint!
namespace HostSystems.API
{
public class Startup
{
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc(options =>
{
var policy = new AuthorizationPolicyBuilder()
.RequireAuthenticatedUser()
.Build();
options.Filters.Add(new AuthorizeFilter(policy));
}).SetCompatibilityVersion(CompatibilityVersion.Latest)
.AddNewtonsoftJson(opt =>
{
opt.SerializerSettings.ReferenceLoopHandling =
Newtonsoft.Json.ReferenceLoopHandling.Ignore;
opt.SerializerSettings.TypeNameHandling = TypeNameHandling.Auto;
opt.SerializerSettings.SerializationBinder =
new CustomJsonSerializationBinder();
opt.SerializerSettings.MetadataPropertyHandling = MetadataPropertyHandling.ReadAhead;
})
;
services.AddCors();
services.Configure<CloudinarySettings>(Configuration.GetSection("CloudinarySettings"));
services.AddScoped<IHsRepository, HsRepository>();
services.AddScoped<PermissionService>();
services.AddTransient<Seed>();
services.AddTransient<GeneralMap>();
services.AddTransient<EventMap>();
services.AddTransient<LegalEntityMap>();
services.AddTransient<UserMap>();
services.AddTransient<ProviderMap>();
services.AddTransient<LicenseeMap>();
services.AddTransient<SItemMap>();
services.AddScoped<LogUserActivity>();
services.AddSignalR();
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app,
IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseExceptionHandler(builder =>
{
builder.Run(async context =>
{
context.Response.StatusCode = (int)HttpStatusCode.InternalServerError;
var error = context.Features.Get<IExceptionHandlerFeature>();
if (error != null)
{
context.Response.AddApplicationError(error.Error.Message);
await context.Response.WriteAsync(error.Error.Message);
}
});
});
}
app.UseCors(x =>
x.WithOrigins("http://localhost:5000", "http://localhost:4200")
.AllowAnyHeader().AllowAnyMethod().AllowCredentials());
// app.UseForwardedHeaders(new ForwardedHeadersOptions
// {
// ForwardedHeaders = ForwardedHeaders.XForwardedFor | ForwardedHeaders.XForwardedProto
// });
app.UseAuthentication();
app.UseDefaultFiles();
app.UseStaticFiles();
// This method is obsolete and will be removed in a future version
app.UseSignalR(routes =>
{
routes.MapHub<TestHub>("/loopy");
});
// This got depreciated with .net core v 3.1 -> for now there is no fallback, you have to find the alternative solution
// app.UseMvc(routes =>
// {
// routes.MapSpaFallbackRoute(
// name: "spa-fallback",
// defaults: new { controller = "Fallback", action = "Index" }
// );
// });
}
}
}
As I am not sure where to start, please let me know what else could be helpful.

ASP.NET Core API returning 401 on call from React client

I'm working on a brand new ASP.NET Core 2.1 SPA app with React/Redux front end. I've implemented jwt authentication which gets its token from Azure AD B2C.
When I analyze the network tab for my API call to the backend, I see that token is placed in the header -- see below:
Here's the code for my fetch call:
import { fetchOptionsGet, fetchOptionsPost, parseJSON } from '../../utils/fetch/fetch-options';
export const getData = () => {
return (dispatch) => fetch("/api/accounts/test", fetchOptionsGet())
.then((response) => {
if (response.ok) {
parseJSON(response)
.then(result => {
// Do something here...
})
}
})
};
Here's my fetch options:
export const fetchOptionsGet = () => {
const token = authentication.getAccessToken();
debugger
return {
method: 'GET',
mode: 'cors',
headers: {
"Content-Type": "application/json",
"Authentication": "Bearer " + token
}
}
}
Notice the debugger in the above code to make sure I'm getting the token which confirms I have the token -- not to mention it's my network call as well.
Here's the ConfigureServices() method in Startup.cs:
public void ConfigureServices(IServiceCollection services)
{
services.AddAuthentication(options => {
options.DefaultScheme = JwtBearerDefaults.AuthenticationScheme;
})
.AddJwtBearer(jwtOptions => {
jwtOptions.Authority = $"https://login.microsoftonline.com/tfp/{Configuration["AzureAdB2C:Tenant"]}/{Configuration["AzureAdB2C:Policy"]}/v2.0/";
jwtOptions.Audience = Configuration["AzureAdB2C:ClientId"];
jwtOptions.Events = new JwtBearerEvents
{
OnAuthenticationFailed = AuthenticationFailed
};
});
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
// In production, the React files will be served from this directory
services.AddSpaStaticFiles(configuration =>
{
configuration.RootPath = "ClientApp/build";
});
}
Here's the Configure() method in Startup.cs:
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseExceptionHandler("/Error");
app.UseHsts();
}
app.UseHttpsRedirection();
ScopeRead = Configuration["AzureAdB2C:ScopeRead"];
app.UseAuthentication();
app.UseStaticFiles();
app.UseSpaStaticFiles();
app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller}/{action=Index}/{id?}");
});
app.UseSpa(spa =>
{
spa.Options.SourcePath = "ClientApp";
if (env.IsDevelopment())
{
spa.UseReactDevelopmentServer(npmScript: "start");
}
});
}
Here's the API controller:
[Produces("application/json")]
[Route("api/[controller]")]
[Authorize]
public class AccountsController : Controller
{
[HttpGet("test")]
public async Task<IActionResult> Test()
{
// Do something here...
}
}
I put a break point right at the beginning of my Test() API method but I'm not hitting it. Without the [Authorize] attribute, I'm able to hit the Test() API method and get my data. So, something in the pipeline is blocking the call before I even hit the API method.
I also tried specifying the authorization scheme in my API controller with the following but that didn't make any difference. Still getting a 401 error.
[Authorize(AuthenticationSchemes = JwtBearerDefaults.AuthenticationScheme)]
Any idea where I'm making a mistake here?
The header name should be Authorization.
export const fetchOptionsGet = () => {
const token = authentication.getAccessToken();
debugger
return {
method: 'GET',
mode: 'cors',
headers: {
"Content-Type": "application/json",
"Authorization": "Bearer " + token //<--
}
}
}

Resources