使用 guice 将 CrossOriginFilter 添加到 dropwizard

Sae*_*var 3 java ajax guice cross-domain dropwizard

我对 dropwizard 和 guice 还很陌生。当我在本地通过 ajax 代码访问 api 时,浏览器控制台上出现以下错误。请求的资源上不存在“Access-Control-Allow-Origin”标头。因此,不允许访问来源“null”。

研究该错误后,许多人建议将 CrossORiginFilter 添加到我的 dropwizard 代码中。这是通过 env.addFilter 完成的但我正在尝试使用 Guice。这是我的主课

public static void main( String[] args ) throws Exception
{
    new TListService().run( args );
}

@Override
public void initialize( Bootstrap<TListServiceConfiguration> bootstrap )
{
    bootstrap.setName( "tlist" );
    bootstrap.addBundle( GuiceBundle.< TListServiceConfiguration > newBuilder().addModule( new JpaPersistModule( this.getClass().getPackage().getName() ) ).setConfigClass( TListServiceConfiguration.class )
            .enableAutoConfig( this.getClass().getPackage().getName() ).build() );
}

@Override
public void run( TListServiceConfiguration config, Environment env ) throws Exception
{        
}
Run Code Online (Sandbox Code Playgroud)

这是我的 ajax 代码:

$(document).ready(function() {
    $('#btnSend').click(function(){
        var apiUrl = $('#txtServer').val() + $("#selectApi").val();
        console.log("URL: " + apiUrl);
        var postData = JSON.parse($('#textData').val());
        console.log(postData);
        console.log(JSON.stringify(postData));
        $.ajax({
            url: apiUrl,
            async: false,
            type: 'POST',
            dataType:"json",
            contentType:"application/json; charset=UTF-8",
            data: JSON.stringify(postData),
        })
        .done(function(data) {
            console.log("success");
            console.log(data);
        })
        .fail(function() {
            console.error("Error");
        })
        .always(function() {
            console.log("complete");
        });
    });     
});
Run Code Online (Sandbox Code Playgroud)

小智 5

首先,创建一个过滤器以允许跨域请求

public class CrossDomainFilter implements Filter {
       public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {

            HttpServletResponse res = (HttpServletResponse) response;

            res.setHeader("Access-Control-Allow-Origin", "*");
            res.setHeader("Access-Control-Allow-Headers", "origin, content-type, accept, authorization");
            res.setHeader("Access-Control-Allow-Credentials", "true");
            res.setHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS, HEAD");
            res.setHeader("Access-Control-Max-Age", "1209600");

            chain.doFilter(request, response);
        }
}
Run Code Online (Sandbox Code Playgroud)

然后,在run()Service 类的方法中添加映射

env.getApplicationContext().addFilter(CrossDomainFilter.class, "/*", EnumSet.of(DispatcherType.REQUEST, DispatcherType.ERROR));

希望这可以帮助。