问题
Hello I'm a newbie in ionic.I want to call post service in ionic but I always get this error ; ""
Failed to load http://mywebservice.com/api: Response to preflight request doesn't pass access control check: The value of the 'Access-Control-Allow-Origin' header in the response must not be the wildcard '*' when the request's credentials mode is 'include'. Origin 'http://localhost:8100' is therefore not allowed access. The credentials mode of requests initiated by the XMLHttpRequest is controlled by the withCredentials attribute.
I have enable Cors in my web service (nancyfx) Even I check it on advanced Rest Service .
And call post service in ionic ;
let headers = new HttpHeaders();
headers = headers
.set("Accept", "application/json")
.set("Content-Type", "application/json")
const params = new HttpParams();
const options = { headers, params, withCredentials: true };
return this.http
.post(
"mywebservice.com/api", headers, options
)do(res => console.log(res));
enter code here
Any help is appricated,thanks !
回答1:
In your ionic .config() you need to set below lines
delete $httpProvider.defaults.headers.common['X-Requested-With'];
$httpProvider.defaults.useXDomain = true;
回答2:
I finally solve my problem by adding these in web.config (enable cors in my webservice ,nancyfx) ,(be aware of adding your custom headers to the Access-Control-Allow-Headers)
<httpProtocol>
<customHeaders>
<add name="Access-Control-Allow-Origin" value="http://localhost:8100"/>
<add name="Access-Control-Allow-Credentials" value="true"/>
<add name="Access-Control-Allow-Headers" value="Origin, X-Requested-With, Content-Type, Accept, Authorization, Content-Disposition, mycustomheaders!" />
<add name="Access-Control-Allow-Methods" value="GET, POST, PUT, DELETE, OPTIONS"/>
</customHeaders>
</httpProtocol>
来源:https://stackoverflow.com/questions/49458696/ionic-post-in-rest-service-error-with-cors-enabled-service