我一直在寻找5个小时左右,但我放弃了。 我的ajax get请求只是不想工作。
var ApiResponce = $.ajax({
url: "http://localhost:18428/api/Reservation/" + userid + "?weekNumber=" + weeknr,
type: 'GET',
headers: {
'Authorization': "bearer " + token,
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Credentials': true,
},
dataType: 'json',
crossDomain: true,
contentType: "application/json",
success: function(responce) {
console.log("success");
console.log(responce);
},
error: function(err) {
console.log("error");
console.log(ApiResponce);
},
});
它连接到标准的C#mvc api,但我得到的只是这个错误:
XMLHttpRequest无法加载http://localhost:18428/api/Reservation/1?weekNumber=1。对预检请求的响应未通过访问控制检查:请求的资源上不存在“Access-Control-Allow-Origin”标头。因此,不允许原点“http://localhost”访问。响应的HTTP状态代码为405。
答案 0 :(得分:2)
如果在服务器端使用Apache Tomcat,则需要在servlet容器上编辑web.xml文件并添加以下行:
<filter>
<filter-name>CorsFilter</filter-name>
<filter-class>org.apache.catalina.filters.CorsFilter</filter-class>
<init-param>
<param-name>cors.allowed.origins</param-name>
<param-value>*</param-value>
</init-param>
<init-param>
<param-name>cors.allowed.methods</param-name>
<param-value>GET, HEAD, POST, PUT, DELETE, OPTIONS</param-value>
</init-param>
<init-param>
<param-name>cors.exposed.headers</param-name>
<param-value>Access-Control-Allow-Origin,Access-Control-Allow-Credentials,X-Bonita-API-Token</param-value>
</init-param>
<init-param>
<param-name>cors.allowed.headers</param-name>
<param-value>Content-Type,X-Requested-With,accept,Origin,Access-Control-Request-Method,Access-Control-Request-Headers,X-Bonita-API-Token</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>CorsFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
注意:可以在Apache Tomcat 7+中运行,请不要忘记重启tomcat。