Search This Blog

Thursday, June 4, 2020

React or Localhsot CORS Error to Solve in Server Side Filters

package com.drvijayy2k2;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import com.product.sr.global.utils.Constants;

/**
 * The Class ContextFilters
 * ******* THIS CONTROLLER IS THE COMMON filter for the API context, this will receive all the request/response ********
 *
 * @author drvijay
 */

@Component
@Order ( 1 )
public class ContextFilters implements Filter, Constants
{


    /*
     * (non-Javadoc)
     * @see javax.servlet.Filter#init(javax.servlet.FilterConfig)
     */
    @Override
    public void init ( FilterConfig arg0 ) throws ServletException
    {
    }

    /*
     * (non-Javadoc)
     * @see javax.servlet.Filter#destroy()
     */
    @Override
    public void destroy ()
    {
    }

    /*
     * (non-Javadoc)
     * @see javax.servlet.Filter#doFilter(javax.servlet.ServletRequest, javax.servlet.ServletResponse, javax.servlet.FilterChain)
     */
    @Override
    public void doFilter ( ServletRequest request, ServletResponse response, FilterChain chain ) throws IOException, ServletException
    {
        try
        {
            HttpServletRequest req = (HttpServletRequest) request;
            HttpServletResponse res = (HttpServletResponse) response;

            res.setHeader ( "Access-Control-Allow-Origin", "*" );
            res.setHeader ( "Access-Control-Allow-Credentials", "true" );
            res.setHeader ( "Access-Control-Allow-Methods", "ACL, CANCELUPLOAD, CHECKIN, CHECKOUT, COPY, DELETE, GET, HEAD, LOCK, MKCALENDAR, MKCOL, MOVE, OPTIONS, POST, PROPFIND, PROPPATCH, PUT, REPORT, SEARCH, UNCHECKOUT, UNLOCK, UPDATE, VERSION-CONTROL" );
            res.setHeader ( "Access-Control-Max-Age", "3600" );
            res.setHeader ( "Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept, Key, Authorization" );


            if ( "OPTIONS".equalsIgnoreCase ( req.getMethod () ) )
            {
                res.setStatus ( HttpServletResponse.SC_OK );
            }
            else
            {
                chain.doFilter ( req, res );
            }

        }
        catch ( Exception e )
        {
            //error
        }
    }

}

No comments:

Hit Counter


View My Stats