Angular2 with ASP.NET Core CORS issues when sending a POST request

There were problems sending a POST request through my Angular 2 service to the ASP.NET Core API. I am currently getting an HTTP 500 error:

"XMLHttpRequest cannot load http: // localhost: 51014 / api / sites . The Access-Control-Allow-Origin header is missing on the requested resource. Http: // localhost: 3000 ', therefore, is not allowed. The response has a status code HTTP 500.

I am not getting this error in GET requests, and as far as I can see, do I have the correct CORS server setup?

Startup.cs

public void ConfigureServices(IServiceCollection services)
    {
        ...

        services.AddCors();
        services.AddMvc();            

        ....
    }

public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
    {
        ...

        app.UseCors(builder =>
            builder.WithOrigins("http://localhost:3000")
                .AllowAnyHeader()
                .AllowAnyMethod());

        app.UseMvc(routes =>
        {
            routes.MapRoute(
                name: "default",
                template: "{controller=Home}/{action=Index}/{id?}");
        });

    }

SitesContoller.cs

// POST: api/Sites
    [HttpPost]
    public async Task<IActionResult> PostSite([FromBody] Site site)
    {
        if (!ModelState.IsValid)
        {
            return BadRequest(ModelState);
        }

        _context.Sites.Add(site);
        try
        {
            await _context.SaveChangesAsync();
        }
        catch (DbUpdateException)
        {
            if (SiteExists(site.Id))
            {
                return new StatusCodeResult(StatusCodes.Status409Conflict);
            }
            else
            {
                throw;
            }
        }

        return CreatedAtAction("GetSite", new { id = site.Id }, site);
    }

My Angular 2 Service:

site.service.ts snippet

public createSite(site: Site): Observable<Site> {
    let headers = new Headers({ 'Content-Type': 'application/json' });
    let options = new RequestOptions({ headers: headers });
    let body = JSON.stringify(site);

    return this.http
        .post(this.apiUrl + 'sites', { body }, options)
        .map((res: Response) => res.json());
}
+4
1

EnableCors SiteController.

[EnableCors(origins: "http://<SOME_SITE>", headers: "*", methods: "*")]
public class SiteController {
.....
}

, , , .

0

Source: https://habr.com/ru/post/1659356/


All Articles