如何解决CORS策略已阻止从来源“ http:// localhost:3000”访问“ http:// localhost:9900 / jaxrs-post-example / rest / customers”的访存
我从https://www.logicbig.com/tutorials/java-ee-tutorial/jax-rs/post-example.html下载了Jersey Java Rest Api示例
当我使用“在服务器上运行”运行该项目时,它接受了来自Postman的以下Rest api命令,并且运行正常:
GET http://localhost:9900/jaxrs-post-example/rest/customers
POST http://localhost:9900/jaxrs-post-example/rest/customers
{
"firstName":"David","lastName":"Parker","school":"CSI","standard":"4","rollNumber":85
}
当我从ReactJS发送相同的命令时,服务器在ReactJS中显示以下错误。
CORS策略阻止从来源“ http:// localhost:3000”访问“ http:// localhost:9900 / jaxrs-post-example / rest / customers”处的访存:对预检请求的响应没有•通过访问控制检查:所请求的资源上不存在“ Access-Control-Allow-Origin”标头。如果不透明的响应可以满足您的需求,请将请求的模式设置为“ no-cors”,以在禁用CORS的情况下获取资源。
要解决此问题,我在RestServer.java中添加了以下内容 (基于How to handle CORS using JAX-RS with Jersey)
@Provider
@PreMatching
public class CorsFilter implements ContainerRequestFilter,ContainerResponseFilter {
/**
* Method for ContainerRequestFilter.
*/
@Override
public void filter(ContainerRequestContext request) throws IOException {
// If it's a preflight request,we abort the request with
// a 200 status,and the CORS headers are added in the
// response filter method below.
if (isPreflightRequest(request)) {
request.abortWith(Response.ok().build());
return;
}
}
/**
* A preflight request is an OPTIONS request
* with an Origin header.
*/
private boolean isPreflightRequest(ContainerRequestContext request) {
return request.getHeaderString("Origin") != null
&& request.getmethod().equalsIgnoreCase("OPTIONS");
}
/**
* Method for ContainerResponseFilter.
*/
@Override
public void filter(ContainerRequestContext request,ContainerResponseContext response)
throws IOException {
// if there is no Origin header,then it is not a
// cross origin request. We don't do anything.
if (request.getHeaderString("Origin") == null) {
return;
}
// If it is a preflight request,then we add all
// the CORS headers here.
if (isPreflightRequest(request)) {
response.getHeaders().add("Access-Control-Allow-Credentials","true");
response.getHeaders().add("Access-Control-Allow-Methods","GET,POST,PUT,DELETE,OPTIONS,HEAD");
response.getHeaders().add("Access-Control-Allow-Headers",// Whatever other non-standard/safe headers (see list above)
// you want the client to be able to send to the server,// put it in this list. And remove the ones you don't want.
"X-Requested-With,Authorization," +
"Accept-Version,Content-MD5,CSRF-Token,Content-Type");
}
// Cross origin requests can be either simple requests
// or preflight request. We need to add this header
// to both type of requests. Only preflight requests
// need the prevIoUsly added headers.
response.getHeaders().add("Access-Control-Allow-Origin","*");
}
}
<web-app>
<display-name>JAX-RS Web Application</display-name>
<servlet>
<servlet-name>jersey-json-example-serlvet</servlet-name>
<servlet-class>com.sun.jersey.spi.container.servlet.ServletContainer</servlet-class>
<init-param>
<param-name>com.sun.jersey.spi.container.ContainerResponseFilters</param-name>
<param-value>com.javacodegeeks.rest.jersey.server.CORSFilter</param-value>
</init-param>
<init-param>
<param-name>com.sun.jersey.config.property.packages</param-name>
<param-value>com.javacodegeeks.rest.jersey.server</param-value>
</init-param>
<init-param>
<param-name>com.sun.jersey.api.json.POJOMappingFeature</param-name>
<param-value>true</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>jersey-json-example-serlvet</servlet-name>
<url-pattern>/rest/*</url-pattern>
</servlet-mapping>
</web-app>
当我尝试使用带有CORS的Flask + Python时,ReactJS的命令运行正常。
ReactJS更改: fetch('http:// localhost:5000 / jaxrs-post-example / rest / customers',
Flask + Python代码:
app = Flask(__name__)
app.config['SECRET_KEY'] = 'xyz'
app.config['CORS_HEADERS'] = 'Content-Type'
#Allow specific origin
cors = CORS(app,resources={r"/jaxrs-post-example/*": {"origins": ["http://localhost:3000"]}})
@app.route('/jaxrs-post-example/rest/customers',methods=['GET','POST'])
def getStudent():
print("You are getting getStudent request")
content = request.json
id = content['id']
name = content['name']
address = content['address']
phoneNumber = content['phoneNumber']
print("id = ",id)
print("name = ",name)
print("address = ",address)
print("phoneNumber = ",phoneNumber)
json_object = JFY({"result": "getStudent is called"})
print("json_results = ",json_object)
print("response for getStudent = ",json_object.get_json())
return json_object
输出完美
127.0.0.1 - - [08/Sep/2020 21:00:40] "OPTIONS /jaxrs-post-example/rest/customers HTTP/1.1" 200 -
127.0.0.1 - - [08/Sep/2020 21:00:41] "POST /jaxrs-post-example/rest/customers HTTP/1.1" 200 -
You are getting getStudent request
id = 2152
name = David
address = 12,new street
phoneNumber = 8765489011
json_results = <Response 39 bytes [200 OK]>
response for getStudent = {'result': 'getStudent is called'}
问题:
- 如何在Jersey Java中实现CORS(类似于Flask + Python)?
- 请提供此问题的解决方案
解决方法
找到解决方法
根据视频: 在JAX-RS项目中启用CORS https://www.youtube.com/watch?v=CDEeOWKza2Q
步骤是:
右键单击任何软件包>新建>过滤器
Java package > com.logicbig.example
Class Name > CorsFilter > Next
Double click /CorsFilter > Pattern > /rest/* > Ok > Next
Ensure > Interface = javax.servlet.Filter > Finish
观察新类(CorsFilter)已创建
删除构造函数
在doFilter下添加以下内容
public void doFilter(ServletRequest request,ServletResponse response,FilterChain chain) throws IOException,ServletException {
HttpServletResponse resp = (HttpServletResponse) response;
resp.addHeader("Access-Control-Allow-Origin","http://localhost:3000");
resp.addHeader("Access-Control-Allow-Headers","*");
resp.addHeader("Access-Control-Allow-Methods","*");
chain.doFilter(request,response);
}
构建路径>外部jar>添加> C://Tomcat/lib/servlet-api.jar
观察:所有错误均已删除
重新启动Tomcat
在服务器上运行
观察:ReactJS中的CORS错误已删除
,您必须从尝试访问的服务启用跨源资源共享。请检查相关链接here。这很好地解释了如何在使用Jersey的JAXRS中实现它。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。