-1

Goal:
Use Axios with put and post method from react TS to Backend WebApi c#.

Problem:
The code doesn't work in relation to CORS.

What part from the backend source code am I missing in order to make backend to retrieve data that is PUT or POST?

Thank you!


React TS

import React from 'react'; import logo from './logo.svg'; import './App.css'; import axios from 'axios';

function App() {

const get = () => {

axios.get("https://localhost:7177/WeatherForecast/GetTestData")
.then(
    response => console.log(response)
);

};

const update = () => { const data = { CandyNumber: Number("1"), Name: "asdf" };

axios.put("https://localhost:7177/WeatherForecast/UpdateTestData", data)
.then(
    response => console.log(response)
);

};

const add = () => { const data = { CandyNumber: Number("1"), content: "asdf" };

axios.post("https://localhost:7177/WeatherForecast/AddTestData", data)
.then(
    response => console.log(response)
);

};

return ( Get Add Uppdate ); }

export default App;


backend

using Microsoft.AspNetCore.Mvc;
using System.Collections.Generic;

namespace WebTest2.Controllers
{
    [ApiController]
    [Route("[controller]")]
    public class WeatherForecastController : ControllerBase
    {
        private static readonly string[] Summaries = new[]
        {
        "Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching"
    };

        private readonly ILogger<WeatherForecastController> _logger;

        public WeatherForecastController(ILogger<WeatherForecastController> logger)
        {
            _logger = logger;
        }


        [HttpGet("GetTestData", Name = "GetTestData")]
        [ProducesResponseType(typeof(List<Test>), StatusCodes.Status200OK)]
        [ProducesResponseType(204)]
        [Produces("application/json")]
        public async Task<IActionResult> GetTestData()
        {
            List<Test> mytest = new List<Test>();

            Test myTest = new Test()
            {
                CandyNumber = 1,
                Name = "asdf"
            };

            Test myTest2 = new Test()
            {
                CandyNumber = 2,
                Name = "asdf"
            };

            mytest.Add(myTest);
            mytest.Add(myTest2);

            return Ok(mytest);
        }


        [HttpPost("AddTestdata", Name = "AddTestdata")]
        public async Task<IActionResult> AddTestdata(Test test)
        {
            List<Test> mytest = new List<Test>();

            Test myTest = new Test()
            {
                CandyNumber = 1,
                Name = "asdf"
            };

            Test myTest2 = new Test()
            {
                CandyNumber = 2,
                Name = "asdf"
            };

            mytest.Add(myTest);
            mytest.Add(myTest2);

            return StatusCode(StatusCodes.Status204NoContent, null);
        }


        [HttpPut("UpdateTestdata", Name = "UpdateTestdata")]
        public async Task<IActionResult> UpdateTestdata(Test test)
        {

            return StatusCode(StatusCodes.Status204NoContent, null);
        }
    }

    public class Test
    {
        public int CandyNumber { get; set; }
        public string Name { get; set; }
    }
}

Program.cs

using Microsoft.OpenApi.Models;
using System.Reflection;

var builder = WebApplication.CreateBuilder(args);

// Add services to the container.

builder.Services.AddControllers();
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer();

builder.Services.AddSwaggerGen(c =>
{
    c.SwaggerDoc("v1", new OpenApiInfo
    {
        Title = ""
    });
});

builder.Services.AddCors(options =>
{
    options.AddPolicy("AllowAllHeaders",
    corsbuilder =>
    {
        corsbuilder.AllowAnyOrigin()
        .AllowAnyHeader()
        .AllowAnyMethod()
        .WithOrigins("http://localhost:3000/");
    });
});







var app = builder.Build();

// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
    app.UseSwagger();
    app.UseSwaggerUI();
}

//--



app.UseHttpsRedirection();

app.UseAuthentication();
app.UseAuthorization();

app.MapControllers();

app.Run();
HelloWorld1
  • 13,688
  • 28
  • 82
  • 145

1 Answers1

0

Add

app.UseCors(x => x
    .AllowAnyMethod()
    .AllowAnyHeader()
    .SetIsOriginAllowed(origin => true) // allow any origin
    .AllowCredentials()); // allow credentials

after " app.UseSwaggerUI();"

HelloWorld1
  • 13,688
  • 28
  • 82
  • 145