问题
Here i am consuming java rest webservices in asp.net,while calling service in asp.net i am using ajax to call webservice,below is the code i have used
$.ajax({
type: "POST",
url: 'http://localhost:9090/EmployeeService/employee/create',
data: { id: 4, first_name:"narayan", last_name:"phone", email:"phone", phone:4545454545 },
contentType: "application/json; charset=utf-8",
dataType: "json",
success: OnSuccessCall,
error: OnErrorCall
});
when i run this i get error saying as below
XMLHttpRequest cannot load http://localhost:9090/EmployeeService/employee/create. 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:64992' is therefore not allowed access.
i googled on this topic i found many answers saying i have to add a custom header (or set of headers) to an individual request and shows me code as below
$.ajax({
url: 'foo/bar',
headers: { 'x-my-custom-header': 'some value' }
});
or
$.ajaxSetup({
headers: { 'x-my-custom-header': 'some value' }
});
// Sends your custom header
$.ajax({ url: 'foo/bar' });
// Overwrites the default header with a new header
$.ajax({ url: 'foo/bar', headers: { 'x-some-other-header': 'some value' } });
here what should i substitute for 'x-some-other-header' and "some value" according to my code.Is this the right way to solve this error or what is the other solution?.Please guide me i am very new to asp.net.
回答1:
Are you purposely trying to submit a request to a different domain? The application port, which follows "localhost:", tends to change unless you set it as static. It seems like the port number has been changed to 64992 instead of 9090
回答2:
I solved it by giving access to cross-domain in server side.As the service was written in java using maven i made it to support cross domain by adding in web.xml page these filters
<filter>
<filter-name>CorsFilter</filter-name>
<filter-class>org.apache.catalina.filters.CorsFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>CorsFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
By adding these in web.xml,i was able to solve the error.
来源:https://stackoverflow.com/questions/34618435/response-to-preflight-request-doesnt-pass-access-control-check-no-access-cont