Copied to clipboard

Flag this post as spam?

This post will be reported to the moderators as potential spam to be looked at


  • Santhosh Sivan 7 posts 77 karma points
    Nov 08, 2024 @ 07:15
    Santhosh Sivan
    0

    Umbraco 13 POST API getting cors error

    Hi everyone,

    The frontend team is using the Umbraco 13 API. The APIs are working fine with the GET method, but when hitting the API with the POST method, it shows a CORS error. How can I fix this?

    This is my Umbraco 13 Program.cs file:

    using ManarEthara.Components.Amenities;
    using ManarEthara.Components.Layout;
    using ManarEthara.Components.Page;
    using ManarEthara.Components.Program;
    using ManarEthara.Components.Shared;
    using ManarEthara.Controllers.Validators;
    using ManarEthara.Factories;
    using ManarEthara.Factory;
    using ManarEthara.Repository;
    using ManarEthara.Services;
    using Azure.Storage.Queues;
    using Azure.Storage.Blobs;
    using Microsoft.Extensions.Configuration;
    using Microsoft.Extensions.Azure;
    using Azure.Core.Extensions;
    using ManarEthara;
    using Azure.Identity;
    
    WebApplicationBuilder builder = WebApplication.CreateBuilder(args);
    
    builder.Services.AddCors(options =>
    {
        options.AddPolicy("AllowAll", policy =>
        {
            policy.AllowAnyOrigin()
                  .AllowAnyMethod()
                  .AllowAnyHeader();
        });
    });
    
    var configuration = builder.Configuration;
    
    
    builder.CreateUmbracoBuilder()
        .AddBackOffice()
        .AddWebsite()
        .AddDeliveryApi()
        .AddComposers()
        .AddAzureBlobMediaFileSystem()
        .ConfigureAuthentication(configuration)
        .Build();
    
    builder.Services.AddSingleton<CaptchaValidator>(new CaptchaValidator(configuration["ApiConfig:recaptchakey"]));
    
    builder.Services.AddTransient<ComponentService>();
    builder.Services.AddTransient<ComponentFactory>();
    builder.Services.AddTransient<ComponentRepository>();
    builder.Services.AddTransient<LayoutService>();
    builder.Services.AddTransient<LayoutFactory>();
    builder.Services.AddTransient<ContentQueryRepository>();
    
    var imageFactory = new ImageFactory(configuration);
    
    Gallery.Initialize(imageFactory);
    Seo.Initialize(imageFactory);
    Banner.Initialize(imageFactory);
    Carousel.Initialize(imageFactory);
    MenuItems.Initialize(imageFactory);
    SecondaryMenuItems.Initialize(imageFactory);
    StoreLinks.Initialize(imageFactory);
    image.Initialize(imageFactory);
    Amenities.Initialize(imageFactory);
    ProgramData.Initialize(imageFactory);
    PageBanner.Initialize(imageFactory);
    InfoContent.Initialize(imageFactory);
    MapView.Initialize(imageFactory);
    
    builder.Services.AddControllers().AddNewtonsoftJson();
    builder.ConfigureKeyVault();
    
    
    WebApplication app = builder.Build();
    app.UseCors("AllowAll");
    await app.BootUmbracoAsync();
    
    
    app.UseUmbraco()
        .WithMiddleware(u =>
        {
            u.UseBackOffice();
            u.UseWebsite();
        })
        .WithEndpoints(u =>
        {
            u.UseInstallerEndpoints();
            u.UseBackOfficeEndpoints();
            u.UseWebsiteEndpoints();
        });
    
    await app.RunAsync();
    
  • Afreed 54 posts 261 karma points
    Nov 08, 2024 @ 08:11
    Afreed
    0

    Hi Santhosh,

    As Umbraco 13's Content Delivery API only supports GET requests, the POST endpoints you’re referring to would likely be custom ones created on your end, correct? Could you share more details about how they’re set up.

  • Santhosh Sivan 7 posts 77 karma points
    Nov 08, 2024 @ 08:21
    Santhosh Sivan
    0

    Hi Afreed,

    Thanks for your reply. I created a POST method function to save the email provided from the frontend, and we save it and display it in the CMS. I’ll share the code for your reference.

    [HttpPost]
    public async Task<IActionResult> newsletter_requests_biennial(NewletterRequestBiennial model) {
        if (model == null) {
            var errorResponse = new Response {
                Status = 400,
                Message = "Invalid data"
            };
    
            return BadRequest(errorResponse);
        }
    
        try {
    
            int recaptchaStatus = model.recaptcha_status ?? 0;
    
            if (recaptchaStatus == 0 && !await _captchaValidator.IsCaptchaValid(model.token)) {
                var errorResponse = new Response {
    
                    code = "CAPTCHA_FAILED"
                };
                return BadRequest(errorResponse);
            }
            var contentService = _contentService;
    
    
            var parentItem = contentService.GetById(Guid.Parse("9d3651d3-16e9-4ed7-a0e0-e360d900f7b9"));
    
            if (parentItem == null) {
                return NotFound("Parent content item not found");
            }
    
            long totalRecords;
    
    
            var existingNewsletterRequest = contentService.GetPagedDescendants(
                parentItem.Id,
                0,
                int.MaxValue,
                out totalRecords,
                null,
                null
            ).FirstOrDefault(node => node.GetValue<string>("email") == model.email);
    
            if (existingNewsletterRequest != null) {
                var errorResponse = new Response {
    
                    code = "EMAIL_EXIST"
                };
                return BadRequest(errorResponse);
            }
    
    
            var newsletterRequestNode = contentService.CreateContent(
                model.email,
                parentItem.GetUdi(),
                "newsletterBiennial");
    
            newsletterRequestNode.SetValue("email", model.email);
    
            contentService.SaveAndPublish(newsletterRequestNode);
    
            var successResponse = new Response {
                Status = 200,
                Message = "Newsletter request created and published successfully"
            };
    
            return Ok(successResponse);
    
        }
        catch (Exception ex) {
    
            var errorResponse = new Response {
                Status = 500,
                Message = ex.Message
            };
    
            return StatusCode(500, errorResponse);
        }
    }
    
  • Afreed 54 posts 261 karma points
    Nov 08, 2024 @ 09:21
    Afreed
    0

    Could you make sure the request is working via Postman or cURL?

    You could try explicitly enabling CORS for the method

    [HttpPost]
    [EnableCors("AllowAll")]
    [Route("newsletter-request")]
    public async Task<IActionResult>newsletter_requests_biennial(NewletterRequestBiennial model)
    
Please Sign in or register to post replies

Write your reply to:

Draft