Skip to content

CORS Error #268

Description

@utkarsh3020

When I hit the API from my frontend react app then I get a CORS error

Frontend Code -
const fetchContacts = async () => { const oauthKeyService = keystore; fetch("https://localhost:44326/OAuth/GetContacts", { method: "GET", headers: { 'Content-Type': 'application/json', 'OAuth-Key-Service': JSON.stringify(oauthKeyService) }, }) .then((response) => response.json()) .then((data) => { console.log("Contacts received:", data); setContacts(data); }) .catch((error) => { console.error("Error fetching contacts:", error); }); };

Backend Code -
`
public ActionResult CreateContact(Customer customer)
{
try
{
var oauthKeyServiceJson = HttpContext.Request.Headers["OAuth-Key-Service"];
var keystore = JsonConvert.DeserializeObject(oauthKeyServiceJson);
// Ensure keystore is initialized
if (keystore == null)
{
return new HttpStatusCodeResult(500, "OAuth KeyStore is not initialized.");
}

            // Fetch the company file
            var cfService = new CompanyFileService(_configuration, null, keystore);
            var companyFile = cfService.GetRange().FirstOrDefault(x => new Version(x.ProductVersion) >= new Version("2013.3"));

            if (companyFile == null)
            {
                return new HttpStatusCodeResult(500, "No valid company file found.");
            }

            // Ensure credentials are valid
            var credentials = new CompanyFileCredentials("Administrator", "");

            // Create contact service and insert customer
            var contactService = new CustomerService(_configuration, null, keystore);
            contactService.Insert(companyFile, customer, credentials);

            return new HttpStatusCodeResult(201, "Customer created successfully");
        }
        catch (ApiValidationException ex)
        {
            Console.WriteLine("Validation Error in CreateContact: " + ex.Message);
            return new HttpStatusCodeResult(400, ex.Message);
        }
        catch (Exception ex)
        {
            Console.WriteLine("Error in CreateContact: " + ex.Message);
            return new HttpStatusCodeResult(500, "An error occurred while creating the customer.");
        }
    }

`

The CORS Error I am getting for both creating contact and fetching contact

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions