java - 当我使用来自前端的 ajax 请求访问 Tomcat、maven 中的 db 时出现 CORS 标头错误
问题描述
所以我创建了这个资源,它返回一个产品数组。
public class MyResource {
/**
* Method handling HTTP GET requests. The returned object will be sent
* to the client as "text/plain" media type.
*
* @return String that will be returned as a text/plain response.
*/
@GET
@Produces(MediaType.APPLICATION_JSON)
public Object getbook()
{
Products p = new Products();
Gson gson = new GsonBuilder().create();
return gson.toJson(p.getAll());
}
但是当我从我的前端调用这个 api 时,它说从源 'http://localhost:8083' 访问 XMLHttpRequest 在 'http://localhost:8085/demoRest/webapi/myresource' 已被 CORS 策略阻止:否请求的资源上存在“Access-Control-Allow-Origin”标头。
这是我的ajax请求
$(function() {
var val = "";
$("#submit").click(function(event){
event.preventDefault();
$.ajax({
type: "GET",
dataType:"json",
url: "http://localhost:8085/demoRest/webapi/myresource",
success: function(data) {
console.log("response:" + data);
//$.each(data, function(j, pdata) {
// val= val + "[ "+pdata.title +" " + pdata.author +"]";
// });
// $("#data").text(val);
},
error: function(jqXHR, textStatus, errorThrown) {
console.log(' Error in processing! '+textStatus);
}
});
});
});
我的 Webxml
<servlet>
<servlet-name>Jersey Web Application</servlet-name>
<servlet-class>org.glassfish.jersey.servlet.ServletContainer</servlet-class>
<init-param>
<param-name>jersey.config.server.provider.packages</param-name>
<param-value>com.demoRest</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>Jersey Web Application</servlet-name>
<url-pattern>/webapi/*</url-pattern>
</servlet-mapping>
使用 tomcat 版本 10
解决方案
所以我想你应该了解 CORS 政策。
https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS
如果您在未经主机 B 许可的情况下从主机 A 向主机 B 使用 XMLHttpRequest,用户将阻止该请求。
但是,我们可以通过在主机 B 上添加一些标头来绕过 CORS。后端 api 经常使用此策略来处理来自不同主机的许多不同请求。
你可以在这里举个例子:
((HttpServletResponse) servletResponse).addHeader("Access-Control-Allow-Origin", "*");
((HttpServletResponse) servletResponse).addHeader("Access-Control-Allow-Methods","GET, OPTIONS, HEAD, PUT, POST");
更多详情:
https://howtodoinjava.com/java/servlets/java-cors-filter-example/
推荐阅读
- nix - 我将我的 nixos 频道更改为不稳定,为什么我的包仍然没有更新?
- php - 当添加新帖子时,laravel 5.6 向 10,000 多个订阅者发送邮件
- c# - 为什么要使用覆盖?
- sql-server - SQL Server 内存中 OLTP (Hekaton) 中的动态更新或等效脚本
- node.js - Angular 6+,能够从应用程序安全地创建用户
- ansible - 来自打包脚本的 Ansible 变量
- php - PHP 从 JSON 数组中获取值
- kubernetes - Rancher v2.0 提议 openebs 部署使用 v0.6.0 helm 模板
- javascript - 我的程序无法正常运行,当我单击“添加播放器”按钮时,没有文档添加到 mongo
- intellij-idea - intelliJ 将 Bootstrap 类显示为拼写错误