I'm working on a basic webapi project with default controllers. I need to access the same values from an HTML page using an ajax request.
Key Points:
- Retrieve the token using the token method
- Pass the token to get the values
Client-Side:
Below is my HTML page with two buttons. The first button is used to get the token, and then I manually update the header to fetch the values using the second button.
<html>
<head>
<script src="https://code.jquery.com/jquery-3.2.1.min.js" integrity="sha256-hwg4gsxgFZhOsEEamdOYGBf13FyQuiTwlAQgxVSNgt4="
crossorigin="anonymous"></script>
<script type="text/javascript">
$(document).ready(function () {
// Code for token request
// Code for data request
});
</script>
</head>
<body>
<button id="btnToken" name="btnToken">Get Token</button>
<button id="btnData" name="btnData">Get Data</button>
</html>
Server-Side:
I have enabled CORS in the code and have the following in my API configuration:
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
// Configuration settings
}
}
I also added a preflight request in Global.asax as shown below:
protected void Application_BeginRequest()
{
// Code for preflight request
}
However, when checking in Chrome, I encountered the following error in the console:
No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access.
In IE, the error appears as:
Origin file: not found in Access-Control-Allow-Origin header.
Not sure what I might have done wrong here. Any guidance would be appreciated.