Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin'

孤街浪徒 提交于 2020-01-07 03:04:11

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!