RESTful JAX-RS API Access

I am creating an implementation RESTfulthat includes both the server and some clients. The server is running and running in a cloud service.

When I try to access a resource on a JavaScriptweb client through, XMLHttpRequestI get the following errors.

In Chrome:

> XMLHttpRequest cannot load
> http://someserver.com/someresource.
> No 'Access-Control-Allow-Origin' header is present on the requested
> resource. Origin 'null' is therefore not allowed access.

In Firefox:

Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://someserver.com/someresource. (Reason: CORS header 'Access-Control-Allow-Origin' missing).

I read other recommendations recommending

req.setRequestHeader("Access-Control-Allow-Origin", "*");

But I had no luck with that.

I am wondering if the problem is related to any configuration that must be done on the server side in order to allow calls to be received and processed correctly.

Could you help me solve this problem?

+4
source share
1 answer

.

response.addHeader("Access-Control-Allow-Origin", "*");
response.addHeader("Access-Control-Allow-Methods", "GET, PUT, POST, OPTIONS, DELETE");
response.addHeader("Access-Control-Allow-Headers", "Content-Type");
response.addHeader("Access-Control-Max-Age", "86400");

Jax-RS: ContainerResponseFilter

package com.xyz.package;

import java.io.IOException;

import javax.ws.rs.container.ContainerRequestContext;
import javax.ws.rs.container.ContainerResponseContext;
import javax.ws.rs.container.ContainerResponseFilter;
import javax.ws.rs.ext.Provider;

@Provider
public class CORSFilter implements ContainerResponseFilter {

   @Override
   public void filter(final ContainerRequestContext requestContext,
                      final ContainerResponseContext crc) throws IOException {
      crc.getHeaders().add("Access-Control-Allow-Origin", "*");
      crc.getHeaders().add("Access-Control-Allow-Headers", "origin, content-type, accept, authorization");
      crc.getHeaders().add("Access-Control-Allow-Credentials", "true");
      crc.getHeaders().add("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS, HEAD");
      crc.getHeaders().add("Access-Control-Max-Age", "1209600");
   }

}
0

Source: https://habr.com/ru/post/1608617/


All Articles