Deep
In the below investigation as API, I use http://example.com instead of http://myApiUrl/login from your question, because this first one working. I assume that your page is on http://my-site.local:8088.
NOTE: The API and your page have different domains!
The reason why you see different results is that Postman:
- set header
Host=example.com
(your API) - NOT set header
Origin
- Postman actually not use your website url at all (you only type your API address into Postman) — he only send request to API, so he assume that website has same address as API (browser not assume this)
This is similar to browsers’ way of sending requests when the site and API has the same domain (browsers also set the header item Referer=http://my-site.local:8088
, however I don’t see it in Postman). When Origin
header is not set, usually servers allow such requests by default.
This is the standard way how Postman sends requests. But a browser sends requests differently when your site and API have different domains, and then CORS occurs and the browser automatically:
- sets header
Host=example.com
(yours as API) - sets header
Origin=http://my-site.local:8088
(your site)
(The header Referer
has the same value as Origin
). And now in Chrome’s Console & Networks tab you will see:
When you have Host != Origin
this is CORS, and when the server detects such a request, it usually blocks it by default.
Origin=null
is set when you open HTML content from a local directory, and it sends a request. The same situation is when you send a request inside an <iframe>
, like in the below snippet (but here the Host
header is not set at all) — in general, everywhere the HTML specification says opaque origin, you can translate that to Origin=null
. More information about this you can find here.
fetch('http://example.com/api', {method: 'POST'});
Look on chrome-console > network tab
If you do not use a simple CORS request, usually the browser automatically also sends an OPTIONS request before sending the main request — more information is here. The snippet below shows it:
fetch('http://example.com/api', {
method: 'POST',
headers: { 'Content-Type': 'application/json'}
});
Look in chrome-console -> network tab to 'api' request.
This is the OPTIONS request (the server does not allow sending a POST request)
You can change the configuration of your server to allow CORS requests.
Here is an example configuration which turns on CORS on nginx (nginx.conf file) — be very careful with setting always/"$http_origin"
for nginx and "*"
for Apache — this will unblock CORS from any domain (in production instead of stars use your concrete page adres which consume your api)
Here is an example configuration which turns on CORS on Apache (.htaccess file)
Hello, this is my request:
axios({ method: 'POST', url:
${SERVER_ADDRESS}/api/v1/manager/restaurant/${restaurantName}/payment-methods, crossDomain: true, data: { payment_methods: checkedPayments }, }) .then(() => { dispatch(loadPayments(restaurantName)); }).catch((error) => { console.log(error); dispatch(paymentsError()); });
the server is laravel 5, it is responding with:
XMLHttpRequest cannot load http://localhost:8000/api/v1/manager/restaurant/accusamus/payment-methods. Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:3000' is therefore not allowed access.
Server headers are set with CORS middleware like this:
return $next($request)
->header("Access-Control-Expose-Headers", "Access-Control-*")
->header("Access-Control-Allow-Headers", "Access-Control-*, Origin, X-Requested-With, Content-Type, Accept")
->header('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS, HEAD')
->header('Access-Control-Allow-Origin', '*')
->header('Allow', 'GET, POST, PUT, DELETE, OPTIONS, HEAD');
Theese are the response headers, which I get when I use postman:
Access-Control-Allow-Headers →Access-Control-, Origin, X-Requested-With, Content-Type, Accept
Access-Control-Allow-Methods →GET, POST, PUT, DELETE, OPTIONS, HEAD
Access-Control-Allow-Origin →
Access-Control-Expose-Headers →Access-Control-*
Allow →GET, POST, PUT, DELETE, OPTIONS, HEAD
Cache-Control →no-cache
Connection →close
Content-Type →text/html; charset=UTF-8
Date →Sat, 03 Dec 2016 10:33:04 GMT
Host →localhost:8000
X-Powered-By →PHP/7.0.13
X-RateLimit-Limit →60
X-RateLimit-Remaining →59
phpdebugbar-id →0ff14bef1824f587d8f278c87ab52544
AXIOS sends preflight which is:
Request URL:http://localhost:8000/api/v1/manager/restaurant/accusamus/payment-methods
Request Method:OPTIONS
Status Code:200 OK
Remote Address:[::1]:8000
Response Headers
view source
Allow:GET,HEAD,POST
Cache-Control:no-cache
Connection:close
Content-Type:text/html; charset=UTF-8
Date:Sat, 03 Dec 2016 10:25:27 GMT
Host:localhost:8000
X-Powered-By:PHP/7.0.13
Request Headers
view source
Accept:/
Accept-Encoding:gzip, deflate, sdch, br
Accept-Language:en-US,en;q=0.8
Access-Control-Request-Headers:content-type
Access-Control-Request-Method:POST
Connection:keep-alive
Host:localhost:8000
Origin:http://localhost:3000
Referer:http://localhost:3000/restaurant-profile/payment
User-Agent:Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/54.0.2840.98 Safari/537.36
Am I doing something wrong? I can’t figure it how to do this. Witch Chrome plugin CORS everything works fine, but this is not the way.
Please help, help is really appreciated, spent hours with this.
In this article we are going to few possible fixes we can apply when we get an error “Response to preflight request doesn’t pass access control check: No ‘Access-Control-Allow-Origin’ header is present on the requested resource. Origin ‘http://localhost:58018’
is therefore not allowed access”. We get this error when we are trying to get some data from another origin may be via an AJAX call.
In this post, we will discuss the solutions for this error in detail and we will also discuss Cross Origin Requests. Here I am going to use Visual
Studio 2015, Web API 2. Hope you will like this.
Background
Hosted
Web API on a server, and what that API does is, it will just return the data in JSON format.
But when we try to consume this Web API via an Ajax call, was getting the error “No ‘Access-Control-Allow-Origin’ header is present on the requested resource”. Solved the same issues in different ways. Here we are going to share those.
Using the code
Assume that you have created a Web API and hosted it on your server. If you are new to Web API, you can always get some information from here Articles
Related To Web API .
We all will have some situations where we need to fetch some data from another domain or another site, right? If it is from the same site, you won’t be facing any issues at all. Like you are calling an Ajax call from the page www.SibeeshPassion.com/Receiver.html
to www.SibeeshPassion.com/Sender.html to get the data, here the origin is same. and therefore you will get the data. What happens is when the sender and receiver are not of the same origin. Like you need to get the data from www.Microsoft.com by an Ajax call
in www.SibeeshPassion.com/Receiver.html. The browser will not allow you to get the sensitive data from other domain, for the security purpose your browser will return you “No ‘Access-Control-Allow-Origin’”. To overcome this, we have something called Cross
Origin Resource Sharing (CORS). Basically, the process of allowing other sites to call your Web API is called CORS. According to W3
Org CORS is a standard which tells server to allow the calls from other origins given. It is much secured than using JSONP(Previously we had been using JSON for getting the data from other domains.).
Fix To No Access-Control-Allow-Origin header is present
We can fix this issue in two ways,
- By using Microsoft.AspNet.WebApi.Cors
-
By adding header information in Web.config
We will explain both now.
By using Microsoft.AspNet.WebApi.Cors
To work with this fix, you must include the package By using Microsoft.AspNet.WebApi.Cors from
Manage Nuget window.CORS_In_Manage_NuGet_Package
Now got to App_Start folder from your solution. Then click on the file WebApiConfig.cs,
this is the file where we set the configuration for our Web API.Web_API_Config_Class_File
Then you can add the preceding codes in the static function Register.
var cors = new EnableCorsAttribute("*", "*", "*");
config.EnableCors(cors);
IF you do this, the CORS will be applied globally for all the Web API controller you have. This is the easiest way of doing it. Now if you want to see the metadata of EnableCorsAttribute,
you can see find it below.// Summary:
// Initializes a new instance of the System.Web.Http.Cors.EnableCorsAttribute class.
//
// Parameters:
// origins:
// Comma-separated list of origins that are allowed to access the resource. Use
// "*" to allow all.
//
// headers:
// Comma-separated list of headers that are supported by the resource. Use "*" to
// allow all. Use null or empty string to allow none.
//
// methods:
// Comma-separated list of methods that are supported by the resource. Use "*" to
// allow all. Use null or empty string to allow none.
public
EnableCorsAttribute(
string
origins,
string
headers,
string
methods);
As it is mentioned, it accepts the parameters origins, headers, methods. Here we pass * to all the three parameters to make everything to be allowable.
You can also try the same as below in the Register function. Here we are going to apply CORS for a particular controller, which means it will be applied for all the actions in the controller. Before that make sure you have added the preceding code in your WebApiConfig.cs
fileAnd in the API controller, you need to set the origins, headers, methods as preceding.
using
System;
using
System.Collections.Generic;
using
System.IO;
using
System.Linq;
using
System.Net;
using
System.Net.Http;
using
System.Web.Http;
using
Newtonsoft.Json;
using
Newtonsoft.Json.Converters;
using
System.Configuration;
using
System.Data;
using
System.Data.SqlClient;
using
System.Runtime.Serialization;
using
System.Text;
using
System.Web;
using
System.Web.Http.Cors;
namespace
APIServiceApplication.Controllers
{
[EnableCors(origins:
"*"
, headers:
"*"
, methods:
"*"
)]
public
class
DefaultController : ApiController{
}
}
Make sure that you have added namespace using System.Web.Http.Cors; to use
CORS. You can always disable CORS in an action by using [DisableCors].namespace
APIServiceApplication.Controllers
{
[EnableCors(origins:
"*"
, headers:
"*"
, methods:
"*"
)]
public
class
DefaultController : ApiController{
[DisableCors]
public
string
XMLData(string
id){
return
"Your requested product"
+ id;}
}
}
Here we have disabled CORS for the action XMLData. And again if you need to
apply CORS only in a single action, you can do that as follows.namespace
APIServiceApplication.Controllers
{
public
class
DefaultController : ApiController{
[EnableCors(origins:
"*"
, headers:
"*"
, methods:
"*"
)]
public
string
XMLData(string
id){
return
"Your requested product"
+ id;}
}
}
Hope you are aware of how to enable CORS now.
By adding header information in Web.config
Another fix we can do is that add some tags in our Web.config file.
<
system.webServer
>
<
httpProtocol
>
<
customHeaders
>
<
add
name
=
"Access-Control-Allow-Origin"
value
=
"*"
/>
<
add
name
=
"Access-Control-Allow-Headers"
value
=
"Content-Type"
/>
<
add
name
=
"Access-Control-Allow-Methods"
value
=
"GET,POST,PUT,DELETE,OPTIONS"
/>
<
add
name
=
"Access-Control-Allow-Credentials"
value
=
"true"
/>
</
customHeaders
>
</
httpProtocol
>
</
system.webServer
>
As you can see we have added keys with value for the listed items.
- Access-Control-Allow-Origin (For Origin)
- Access-Control-Allow-Headers (For Headers)
-
Access-Control-Allow-Methods (For Methods)
Now if you go to your server and check, you can see that all the things are configured perfectly. Configured the API on the server IIS, so going to see Response Header settings in IIS.
Go to the command window and type inetmgr and click OK, your IIS will open shortly, now find your Web API which you have already configured under Default Web Site. Before doing this, please make sure that you have configured IIS in your windows. If you don’t
know how to configure, strongly recommend you to read Configure IIS in Windows.Configured_Web_API_in_IIS
Go to Features View and double click on HTTP Response Headers under IIS category.
HTTP_Response_Headers_In_IIS
You can see all the settings has been configured there.
HTTP_Response_Headers_Available
That’s all, now if you run your application, you will be able to fetch the data from your Web API.
Conclusion
Miss anything that you may think which is needed? Have you ever faced this issue? Did you try Web API yet? Hope you liked this article. Please share your valuable suggestions and feedback.