I have literally seen thousands of these "WCF" questions on the internet so far, but I am beginning to think that it is impossible. Please someone tell me I am wrong...
Background: I am working with a Self Hosted WCF Service (therefore Global.asax.cs won't help here). Also the endpoints are defined programatically. The contract is decorated with WebInvoke(Method="POST") and I am making a JQuery call to the service.
The preflight works initially with the OPTIONS method but the POST method fails with 405 Method Not Allowed. Also GET functions work perfectly.
I have been searching the internet and experimenting for about a month now and it just will not budge. This service already responds fine to another client calling it through TCP... Please could some genius help me out. Thanks
PS: What I thought was really weird about the the POST response, is the Allow: OPTIONS... Surely that should not be there?
CORS
public class CORSEnablingBehavior : BehaviorExtensionElement, IEndpointBehavior
{
public void ApplyDispatchBehavior(ServiceEndpoint endpoint, System.ServiceModel.Dispatcher.EndpointDispatcher endpointDispatcher)
{
var requiredHeaders = new Dictionary<string, string>();
requiredHeaders.Add("Access-Control-Allow-Origin", "*");
requiredHeaders.Add("Access-Control-Allow-Methods", "POST, GET, PUT, DELETE, OPTIONS");
requiredHeaders.Add("Access-Control-Allow-Headers", "Origin, Cache-Control, Connection, Pragma, Content-Length, Content-Type, Accept, Accept-Encoding, Accept-Language, Host, User-Agent");
endpointDispatcher.DispatchRuntime.MessageInspectors.Add(new CORSHeaderInjectingMessageInspector(requiredHeaders));
}
app.config
<system.serviceModel>
<behaviors>
<endpointBehaviors>
<behavior name="SOAPDemoEndpointBehavior">
</behavior>
<behavior>
<webHttp/>
<crossOriginResourceSharingBehavior/>
</behavior>
</endpointBehaviors>
</behaviors>
<serviceHostingEnvironment aspNetCompatibilityEnabled="true" />
<extensions>
<behaviorExtensions>
<add name="crossOriginResourceSharingBehavior" type="Application.Host.CORSEnablingBehavior, Application.Host, Version=1.0.0.0, Culture=neutral"/>
</behaviorExtensions>
</extensions>
<bindings>
<basicHttpBinding>
<binding name="OrdersMappingSoap"/>
</basicHttpBinding>
<!--2015-08-26-->
<webHttpBinding>
<binding name="webHttpBindingWithJson"
crossDomainScriptAccessEnabled="true" />
</webHttpBinding>
Interface
[OperationContract(Name = "Relational")]
[FaultContract(typeof(ValidationFault))]
[WebInvoke(Method = "POST", UriTemplate = "GetCustomerRelational", RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.Wrapped)]
CustomerFullModel GetCustomerRelational(int clientHandle, object customerID, bool loadRelationalData);
JQuery
jQuery.ajax({
crossDomain: true,
type: "POST",
contentType: "application/json",
url: "http://localhost:8086/CustomerService/rest/GetCustomerRelational/",
data: JSON.stringify({
"clientHandle": 1824,
"customerID": "ABB029",
"loadRelationalData": true
}),
dataType: "json",
success: function(result) {
console.log("Success...");
document.getElementById("lblResponse").innerHTML = "Success: " + JSON.stringify(result.NormalResult);
},
error: function(x, s, t) {
console.log("Error...");
document.getElementById("lblResponse").innerHTML = x.responseText;
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Preflight Request
OPTIONS http://localhost:8086/CustomerService/rest/GetCustomerRelational/ HTTP/1.1
Host: localhost:8086
Connection: keep-alive
Access-Control-Request-Method: POST
Origin: null
User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/44.0.2403.157 Safari/537.36
Access-Control-Request-Headers: accept, content-type
Accept: */*
Referer: http://stacksnippets.net/js
Accept-Encoding: gzip, deflate, sdch
Accept-Language: en-US,en;q=0.8
Preflight Response
HTTP/1.1 200 OK
Content-Length: 0
Server: Microsoft-HTTPAPI/2.0
Access-Control-Allow-Origin: *
Access-Control-Allow-Methods: POST, GET, PUT, DELETE, OPTIONS
Access-Control-Allow-Headers: Origin, Cache-Control, Connection, Pragma, Content-Length, Content-Type, Accept, Accept-Encoding, Accept-Language, Host, User-Agent
Date: Wed, 26 Aug 2015 13:13:59 GMT
POST Request
POST http://localhost:8086/CustomerService/rest/GetCustomerRelational/ HTTP/1.1
Host: localhost:8086
Connection: keep-alive
Content-Length: 69
Accept: application/json, text/javascript, */*; q=0.01
Origin: null
User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/44.0.2403.157 Safari/537.36
Content-Type: application/json
Referer: http://stacksnippets.net/js
Accept-Encoding: gzip, deflate
Accept-Language: en-US,en;q=0.8
{"clientHandle":1824,"customerID":"ABB029","loadRelationalData":true}
POST Response
HTTP/1.1 405 Method Not Allowed
Allow: OPTIONS
Content-Length: 1565
Content-Type: text/html; charset=UTF-8
Server: Microsoft-HTTPAPI/2.0
Access-Control-Allow-Origin: *
Access-Control-Allow-Methods: POST, GET, PUT, DELETE, OPTIONS
Access-Control-Allow-Headers: Origin, Cache-Control, Connection, Pragma, Content-Length, Content-Type, Accept, Accept-Encoding, Accept-Language, Host, User-Agent
Date: Wed, 26 Aug 2015 13:14:02 GMT
<p>Method not allowed.</p>
I figured it out.
The main difference between this WCF and everyone else's, is the fact that mine is self hosted, while everything else is hosted on IIS (mostly).
Thanks to this article ASP.NET Compatibility Mode, the answer lies in the interception of the preflight request. IIS hosted WCF requires the interception be done in the global.asax file as follows:
protected void Application_BeginRequest(object sender, EventArgs e)
{
if (HttpContext.Current.Request.HttpMethod == "OPTIONS")
{
//These headers are handling the "pre-flight" OPTIONS call sent by the browser
HttpContext.Current.Response.AddHeader("Access-Control-Allow-Methods", "POST,GET,PUT,DELETE,OPTIONS");
HttpContext.Current.Response.AddHeader("Access-Control-Allow-Headers", "X-Requested-With,Content-Type");
HttpContext.Current.Response.AddHeader("Access-Control-Allow-Origin", "*");
HttpContext.Current.Response.End();
}
}
This however, is not possible in self hosted WCF. BUT, we can still make use of ASP.NET functionality using this line in the app.config
<serviceHostingEnvironment aspNetCompatibilityEnabled="true" />
Then finally utilize this in the service class:
[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Required)]
public class TestService : ValidationModel, ITestService
{
I realized that it doesn't help just to set this to "Allowed", it must be "Required".
Final finally, in order for the preflight to start, the following code needs to be in the interface and the service:
[OperationContract]
[FaultContract(typeof(ValidationFault))]
[WebInvoke(Method = "OPTIONS", UriTemplate = "*")]
void GetOptions();
public void GetOptions()
{
WebOperationContext.Current.OutgoingResponse.StatusCode = System.Net.HttpStatusCode.OK;
}
Now, POST methods with complex parameters will pass the preflight test and execute the method with a response.
If you are dealing with this case in a self hosted service, the following procedure has worked for me:
Add OPTIONS method into your Interface (the Browser, before calling your POST method, calls OPTIONS to verify the CORS)
[OperationContract]
[WebInvoke(Method = "OPTIONS", UriTemplate = "*")]
void GetOptions();
Implement in your ServiceBehavior class
public void GetOptions()
{
WebOperationContext.Current.OutgoingResponse.Headers.Add("Access-Control-Allow-Origin", "*");
WebOperationContext.Current.OutgoingResponse.Headers.Add("Access-Control-Allow-Methods", "POST");
WebOperationContext.Current.OutgoingResponse.Headers.Add("Access-Control-Allow-Headers", "Content-Type, Accept");
WebOperationContext.Current.OutgoingResponse.StatusCode = System.Net.HttpStatusCode.OK;
}
The class may have to have this attribute:
[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
Related
I'm trying to fetch data from my Jira Cloud instance through the Jira and Jira Agile REST APIs using JavaScript in a browser. Queries to Jira REST API work fine but identical queries to Jira Agile REST API keep failing with the response
Response for preflight has invalid HTTP status code 401.
I'm using Basic Authentication with user ID and an API token obtained from Jira. With cURL and ARC, I'm able to successfully retrieve data both from the Jira REST API and the Jira Agile REST API, so the authentication against both APIs seems to work. In JS I have tried with both fetch() and jquery ajax() and the result was the same.
function fetchFromJira(url, id, token) {
const authorizationString = 'Basic ' + btoa(id + ':' + token);
const options = {
method: 'GET',
headers: {
Authorization: authorizationString,
'Content-Type': 'application/json',
},
};
fetch(url, options)
.then(response => {
if (response.ok) {
return response.json();
} else {
throw new Error(response.status);
}
})
.then(json => {
console.log(json);
})
.catch(error => {
console.log(error);
});
}
fetchFromJira(
'https://fredrikastrom.atlassian.net/rest/api/latest/issue/10000',
'<user id>',
'<API token>'
); // successful
fetchFromJira(
'https://fredrikastrom.atlassian.net/rest/agile/1.0/board',
'<user id>',
'<API token>'
); // fails
The output onto the console looks as follows:
test.js:11 OPTIONS https://fredrikastrom.atlassian.net/rest/agile/1.0/board 401 ()
fetchFromJira # test.js:11
(anonymous) # test.js:33
index.html:1 Failed to load https://fredrikastrom.atlassian.net/rest/agile/1.0/board: Response for preflight has invalid HTTP status code 401.
test.js:23 TypeError: Failed to fetch
test.js:20 {expand: "renderedFields,names,schema,operations,editmeta,changelog,versionedRepresentations", id: "10000", self: "https://fredrikastrom.atlassian.net/rest/api/latest/issue/10000", key: "FAT-1", fields: {…}}
Here are the preflight request and response headers of the successful query to the Jira REST API:
t=3241 [st= 89] HTTP_TRANSACTION_HTTP2_SEND_REQUEST_HEADERS
--> :authority: fredrikastrom.atlassian.net
:method: OPTIONS
:path: /rest/api/latest/issue/10000
:scheme: https
accept: */*
accept-encoding: gzip, deflate, br
accept-language: sv-SE,sv;q=0.9,en-US;q=0.8,en;q=0.7,fi;q=0.6
access-control-request-headers: authorization,content-type
access-control-request-method: GET
cache-control: no-cache
origin: http://127.0.0.1:8080
pragma: no-cache
referer: http://127.0.0.1:8080/test/index.html
user-agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/67.0.3396.62 Safari/537.36
t=3241 [st= 89] -HTTP_TRANSACTION_SEND_REQUEST
t=3241 [st= 89] +HTTP_TRANSACTION_READ_HEADERS [dt=68]
t=3278 [st=126] HTTP2_STREAM_UPDATE_SEND_WINDOW
--> delta = 0
--> stream_id = 1
--> window_size = 65535
t=3309 [st=157] HTTP_TRANSACTION_READ_RESPONSE_HEADERS
--> HTTP/1.1 200
status: 200
server: AtlassianProxy/1.15.8.1
vary: Accept-Encoding
cache-control: no-cache, no-store, no-transform
content-type: text/html;charset=UTF-8
content-encoding: gzip
strict-transport-security: max-age=315360000; includeSubDomains; preload
date: Sat, 12 Oct 2019 06:33:50 GMT
atl-traceid: 519aa518a8e8e5ea
x-arequestid: c68d7b95-3635-49e1-a2fd-971e0502adf5
x-xss-protection: 1; mode=block
timing-allow-origin: *
x-content-type-options: nosniff
set-cookie: atlassian.xsrf.token=7a27221d-39bc-4555-9569-b26a0beb9689_b9e038120f5696c0bac7202f986ee24d3752c6fa_lout; Path=/; Secure
and here are the correspinding headers from the failing request to Jira Agile REST API:
t=5918 [st= 5] HTTP_TRANSACTION_HTTP2_SEND_REQUEST_HEADERS
--> :authority: fredrikastrom.atlassian.net
:method: OPTIONS
:path: /rest/agile/latest/board
:scheme: https
accept: */*
accept-encoding: gzip, deflate, br
accept-language: en-GB,en-US;q=0.9,en;q=0.8
access-control-request-headers: authorization,content-type
access-control-request-method: GET
origin: http://127.0.0.1:8080
referer: http://127.0.0.1:8080/test/index.html
user-agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/67.0.3396.62 Safari/537.36
t=5919 [st= 6] -HTTP_TRANSACTION_SEND_REQUEST
t=5919 [st= 6] +HTTP_TRANSACTION_READ_HEADERS [dt=65]
t=5984 [st=71] HTTP_TRANSACTION_READ_RESPONSE_HEADERS
--> HTTP/1.1 401
status: 401
server: AtlassianProxy/1.15.8.1
vary: Accept
www-authenticate: OAuth realm="https%3A%2F%2Ffredrikastrom.atlassian.net"
cache-control: no-transform
content-type: application/xml;charset=UTF-8
strict-transport-security: max-age=315360000; includeSubDomains; preload
date: Sat, 12 Oct 2019 07:05:10 GMT
atl-traceid: 2caf28fb1cce9a77
x-arequestid: 817e2b89-e3d1-431b-b892-781fc78c9669
x-xss-protection: 1; mode=block
timing-allow-origin: *
x-content-type-options: nosniff
set-cookie: atlassian.xsrf.token=7a27221d-39bc-4555-9569-b26a0beb9689_dafc86c05dbdc472c9b99300b351fe0dd62b305d_lout; Path=/; Secure
content-length: 174
Interestingly, the request headers look slightly different even if the requests are made with the same function where only the requested URLs differ. The succeeding request includes the cache-control and pragma headers, and the accept-language header includes one more language. But none of these should reasonably have any impact on whether the server will accept the preflight request?
Any clue why the one request succeeds and the other one fails?
The AJAX request works fine, but the moment I add a header via beforeSend or headers, an OPTIONS pre-flight request is made and the GET request is aborted.
Code: $.ajax({
type: "GET",
crossDomain: true,
beforeSend: function (xhr)
{
xhr.setRequestHeader("session", $auth);
},
url: $url,
success: function (data) {
$('#something').html(data);
},
error: function (request, error) {
$('#something').html("<p>Error getting values</p>");
}
});
Similar AJAX Request w/o headers specified (the moment I add/modify header, an OPTIONS call is made)
Request GET /api/something?filter=1 HTTP/1.1
Referer http://app.xyz.dj/dashboard
Accept application/json, text/javascript, */*; q=0.01
Accept-Language en-US
Origin http://app.xyz.dj
Accept-Encoding gzip, deflate
User-Agent Mozilla/5.0 (Windows NT 6.3; WOW64; Trident/7.0; MASMJS; rv:11.0) like Gecko
Host 162.243.13.172:8080
DNT 1
Connection Keep-Alive
Cache-Control no-cache
Similar Server Response Header (for GET request)
Response HTTP/1.1 200 OK
Server Apache-Coyote/1.1
Access-Control-Allow-Origin *
Access-Control-Allow-Methods GET, POST, DELETE, PUT, OPTIONS, HEAD
Access-Control-Allow-Headers Content-Type, Accept, X-Requested-With
Access-Control-Allow-Credentials true
Content-Type application/json
Transfer-Encoding chunked
Date Thu, 09 Jan 2014 14:43:07 GMT
What I am doing wrong?
Solved.
Thanks #JasonP for pointers. Changed Server Response Headers from
Access-Control-Allow-Headers:*
to specific ones
Access-Control-Allow-Headers: Content-Type, Accept, X-Requested-With, Session
and now it works!
Server side setup
JsonRoutes.setResponseHeaders({
"Cache-Control": "no-store",
"Pragma": "no-cache",
"Access-Control-Allow-Origin": "*",
"Access-Control-Allow-Methods": "GET, PUT, POST, DELETE, OPTIONS",
"Access-Control-Allow-Headers": "Content-Type, Authorization, X-Requested-With"
});
Client side setup
var getRecentPosts = function (token) {
$.ajax({
url: "http://localhost:3000/publications/recentPostsAndComments",
method: "GET",
headers: {
"Authorization": "Bearer " + token,
"Content-Type": "application/json"
},
// contentType: "application/json",
success: function (data, status, xhr) {
debugger
},
error: function (xhr, status, err) {
debugger
}
});
}
I always get caught inside the error callback because of the following error:
XMLHttpRequest cannot load http://localhost:3000/publications/recentPostsAndComments. No
'Access-Control-Allow-Origin' header is present on the requested
resource. Origin 'http://localhost:5000' is therefore not allowed
access.
Is there anything noticeable that I am missing here?
Update:
in the network tab, I see one option request that succeeds, but I don't see a GET request that's supposed to be sent.
Remote Address:127.0.0.1:3000
Request URL:http://localhost:3000/publications/recentPostsAndComments
Request Method:OPTIONS
Status Code:200 OK
Response Headers
view source
connection:keep-alive
content-type:text/html; charset=utf-8
date:Sat, 19 Sep 2015 23:53:48 GMT
transfer-encoding:chunked
vary:Accept-Encoding
Request Headers
view source
Accept:*/*
Accept-Encoding:gzip, deflate, sdch
Accept-Language:en-US,en;q=0.8,ko;q=0.6
Access-Control-Request-Headers:accept, authorization, content-type, x-requested-with
Access-Control-Request-Method:GET
Cache-Control:no-cache
Connection:keep-alive
Host:localhost:3000
Origin:http://localhost:5000
Pragma:no-cache
Referer:http://localhost:5000/
User-Agent:Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_2) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/45.0.2454.93 Safari/537.36
This is what I sometimes use and it works great.
//Server Side PHP
<?php
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, PUT, POST, DELETE, OPTIONS');
header('Access-Control-Max-Age: 2000');
header('Access-Control-Allow-Headers: Content-Type, Authorization, X- Requested-With');
?>
As you know, it should be placed before any code....
I'm developing an Azure MobileService / CordovaApp setup. The server runs locally and has the following setting to enable CORS:
<add name="Access-Control-Allow-Origin" value="*" />
The api can be called via browser using addresses like
http://localhost:59477/api/item/explore/A/B
The client script that's trying to depict this call is the following:
var client = new WindowsAzure.MobileServiceClient('http://localhost:59477/', 'http://localhost:59477/', '');
GetItems.addEventListener("click",
function ()
{
client.invokeApi("item/explore/A/B",
{
method: "get"
})
.done(
function (results)
{
alert(results.result.count);
},
function (error)
{
var xhr = error.request;
alert('Error - status code: ' + xhr.status + '; body: ' + xhr.responseText);
alert(error.message);
}
);
}
);
What I get is status 405 - Method not allowed, which I don't understand for two reasons:
The invoked Service Action is decorated with the [HttpGet] Attribute
The response headers seem to say GET is fine:
HTTP/1.1 405 Method Not Allowed
Allow: GET
Content-Length: 76
Content-Type: application/json; charset=utf-8
Server: Microsoft-IIS/8.0
X-SourceFiles: =?UTF-8?B?RjpcQ29kZVxGb290UHJpbnRzXGZvb3RwcmludHMuU2VydmVyXEZvb3RwcmludHNTZXJ2aWNlXGFwaVxmb290cHJpbnRcZXhwbG9yZVw1MS4yNzcwMjJcNy4wNDA3ODM=?=
X-Powered-By: ASP.NET
Access-Control-Allow-Origin: *
Date: Sat, 15 Aug 2015 18:08:30 GMT
Any idea what I can do to get this running?
Edit
The Raw request shows that, as already expected by Jeremy Foster, the client sends a request of the type OPTIONS:
OPTIONS http://localhost:59477/api/fp/get?id=1 HTTP/1.1
Host: localhost:59477
Connection: keep-alive
Access-Control-Request-Method: GET
Origin: http://localhost:4400
User-Agent: Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/44.0.2403.155 Safari/537.36
Access-Control-Request-Headers: accept, x-zumo-features, x-zumo-installation-id, x-zumo-version
Accept: */*
Referer: http://localhost:4400/index.html
Accept-Encoding: gzip, deflate, sdch
Accept-Language: de-DE,de;q=0.8,en-US;q=0.6,en;q=0.4
I managed to support this request applying the [HttpOptions] attribute to my action method. Now I get a more or less valid response:
HTTP/1.1 200 OK
Content-Type: text/html; charset=utf-8
Content-Encoding: gzip
Vary: Accept-Encoding
Server: Microsoft-IIS/8.0
X-SourceFiles: =?UTF-8?B?RjpcQ29kZVxGb290UHJpbnRzXGZvb3RwcmludHMuU2VydmVyXEZvb3RwcmludHNTZXJ2aWNlXGFwaVxmcFxnZXRcMQ==?=
X-Powered-By: ASP.NET
Access-Control-Allow-Origin: *
Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type, Accept
Date: Sun, 23 Aug 2015 19:34:21 GMT
Content-Length: 234
...
At least that's what fiddler tells me. The AzureMobileServiceClient throws yet another issue, which roughly translates as:
Cross-Origin request blocked, missing token 'x-zumo-installation-id' in CORS header row 'Access-Control-Allow-Headers' on CORS-Preflight-Channel
Turn on Fiddler and try your api call from the browser and then again using the Mobile Services client and compare your raw HTTP requests to see what's different.
Try to run through the CORS Support section of this blog post: http://azure.microsoft.com/blog/2014/07/28/azure-mobile-services-net-updates/.
A side note: The x-zumo-installation-id error you were getting was because the client requested access for a list of headers (see the Access-Control-Request-Headers in your request) and the server did not return that same list in the Access-Control-Allow-Headers header. Using the MS_CrossDomainOrigins setting as mentioned in the above blog post takes care of this by setting the allowed headers to * (all) by default.
Here is my AngularJS code, (it works fine if I remove the header option).
$http.get(env.apiURL()+'/banks', {
headers: {
'Authorization': 'Bearer '+localStorageService.get('access_token')
}
})
Here is the request:
OPTIONS /banks HTTP/1.1
Host: localhost:8080
Connection: keep-alive
Access-Control-Request-Method: GET
Origin: http://localhost:8081
User-Agent: Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/33.0.1750.146 Safari/537.36
Access-Control-Request-Headers: accept, authorization
Accept: */*
Referer: http://localhost:8081/
Accept-Encoding: gzip,deflate,sdch
Accept-Language: en-US,en;q=0.8,vi;q=0.6
And response:
HTTP/1.1 404 Not Found
Access-Control-Allow-Headers: Accept, Content-Type, Content-Length, Accept-Encoding, X-CSRF-Token, Authorization
Access-Control-Allow-Methods: POST, GET, OPTIONS, PUT, DELETE
Access-Control-Allow-Origin: http://localhost:8081
Content-Type: text/plain; charset=utf-8
Date: Mon, 17 Mar 2014 11:05:20 GMT
Content-Length: 19
I added both Accept and Authorization header but the request still fails?
Does the capitalization (I mean authorization vs Authorization) result in that failure? If yes, how can I make AngularJS stop doing that?
if origin := req.Header.Get("Origin"); origin == "http://localhost:8081" {
rw.Header().Set("Access-Control-Allow-Origin", origin)
rw.Header().Set("Access-Control-Allow-Methods", "POST, GET, OPTIONS, PUT, DELETE")
rw.Header().Set("Access-Control-Allow-Headers",
"Accept, Content-Type, Content-Length, Accept-Encoding, X-CSRF-Token, Authorization")
}
Go server routing code:
r := mux.NewRouter()
r.HandleFunc("/banks", RetrieveAllBank).Methods("GET")
http.ListenAndServe(":8080", r)
OK, the issue because I fotgot to handle the "OPTIONS" request (to make a CORS browser will send a preflight OPTIONS request first and then the 'real' request if accepted by the server).
I only need to modify my Go server (see the comment):
func main() {
r := mux.NewRouter()
r.HandleFunc("/banks", RetrieveAllBank).Methods("GET")
http.ListenAndServe(":8080", &MyServer{r})
}
type MyServer struct {
r *mux.Router
}
func (s *IMoneyServer) ServeHTTP(rw http.ResponseWriter, req *http.Request) {
if origin := req.Header.Get("Origin"); origin == "http://localhost:8081" {
rw.Header().Set("Access-Control-Allow-Origin", origin)
rw.Header().Set("Access-Control-Allow-Methods", "POST, GET, OPTIONS, PUT, DELETE")
rw.Header().Set("Access-Control-Allow-Headers",
"Accept, Content-Type, Content-Length, Accept-Encoding, X-CSRF-Token, Authorization")
}
// Stop here if its Preflighted OPTIONS request
if req.Method == "OPTIONS" {
return
}
// Lets Gorilla work
s.r.ServeHTTP(rw, req)
}