Anindya
Anindya

Reputation: 41

How to put "Access-Control-Allow-Origin: *" header in a sling node

I am facing a CORS ie. Same Origin Policy when I am trying to fetch the web service from the server. All I need to do is to put this Access-Control-Allow-Origin: * header in my sling node. I have tried using the curl command to include the header but it didn't work. So, Please tell me a way so that I can put this header in my apache sling node and resolve this CORS issue.

Thanks in advance.

Upvotes: 2

Views: 2604

Answers (1)

balaji
balaji

Reputation: 794

Write a filter and make sure that it hits for your website only. (you can do that using filter.pattern osgi property) and have the below doFilter method,

    public void doFilter(final ServletRequest req, final ServletResponse res, final FilterChain chain) throws IOException, ServletException {
        final HttpServletRequest request = (HttpServletRequest)req;
        final HttpServletResponse response = (HttpServletResponse)res;
        String origin = request.getHeader("Origin");
        if (origin != null) {
            if (origin.contains("yourwebsitename")) {
                 response.addHeader("Access-control-Allow-Origin", origin);
                 response.addHeader("Access-control-Allow-Methods", "GET, POST, OPTIONS");
            }
        }
        chain.doFilter(request, response);
    }

Thanks, Balaji.

Upvotes: 4

Related Questions