如何使用Vert.x 2.x启用CORS [英] how to enable CORS with Vert.x 2.x

查看:139
本文介绍了如何使用Vert.x 2.x启用CORS的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试使用Angularjs 1.4.5发出跨网域请求。
但是不能成功。我已配置$ httpprovider

I am trying to make cross-domain requests with Angularjs 1.4.5. But can't get success. I have configured $httpprovider

.config(['$httpProvider', function($httpProvider) {
        $httpProvider.defaults.useXDomain = true;
        delete $httpProvider.defaults.headers.common['X-Requested-With'];
        $httpProvider.defaults.headers.common['Accept']= "application/json, text/plain, */*";
        $httpProvider.defaults.headers.put["Content-Type"] = "application/x-www-form-urlencoded;charset=utf-8";
        $httpProvider.defaults.headers.post["Content-Type"] = "application/x-www-form-urlencoded;charset=utf-8";
        $httpProvider.interceptors.push('authenticationFailedInterceptor');
    }])

但仍然无法成功。如何使用Vert.x 2.x http服务器启用CORS支持。

But still con't get success. How to enable CORS support with Vert.x 2.x http server.

CORS在Vert.x 3.x中受支持,但现在我无法升级Vert.x。

CORS is supported in Vert.x 3.x but Right now I can't upgrade Vert.x.

推荐答案

完成启用cors的示例:

Complete example to enable cors:

我们需要创建两个路由匹配器。

We need to create two route matcher.

一个帮助启用cors和其他处理请求。

One helps to enable cors and other handle the requests.

下面是启用cors。它接受所有请求并添加所有需要的标题需要启用cors。之后,我们需要将请求交给实际的路由匹配器处理请求。我们有这个名字secureRoutes。

Below is to enable cors. It Accept all request and add all the required headers needs to enable cors. After that we need to hand over request to the actual route matcher to handle request. We have that by the name secureRoutes.

RouteMatcher routeMatcher = new RouteMatcher();
        routeMatcher.options(".*",new Handler<HttpServerRequest>() {
            @Override
            public void handle(final HttpServerRequest request) {
                request.response().putHeader("Access-Control-Allow-Origin", "*");
                request.response().putHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE");
                request.response().putHeader("Access-Control-Allow-Headers", "accept, authorization, content-type, email");
                request.response().end();
            }
        })
        .all(".*",new Handler<HttpServerRequest>() {
            @Override
            public void handle(final HttpServerRequest request) {
                request.response().putHeader("Access-Control-Allow-Origin", "*");
                secureRoutes.getRouteMatcher().handle(request);
            }
        });

另一个路线匹配器:

public class SecureRoutes {
private static final RouteMatcher routeMatcher = new RouteMatcher();
@Inject
protected Container container;
@Inject
private SigninController signinController;
@Inject
private SignupController signupController;
@Inject
private OauthController oauthController;
@Inject
ClientNetworkSignalController clientNetworkSignalController;

public void initRoutes() {
    // APP routes. they use User token for authentication


    routeMatcher.get("/", new Handler<HttpServerRequest>() {
        @Override
        public void handle(final HttpServerRequest request) {
            request.response().putHeader("Cache-Control",
                    "public, max-age=86400");
            request.response().sendFile("web/public/index.html");
        }
    });


    routeMatcher.post("/signin", signinController.signin());
    routeMatcher.post("/signup", signupController.signup());
    routeMatcher.post("/oauth2/token", oauthController.token());
    routeMatcher.post("/oauth2/invalidate_token", oauthController.invalidateToken());

}

public RouteMatcher getRouteMatcher() {
    return routeMatcher;
}

}

现在最终添加requestHandler到服务器:

Now finally add requestHandler to server:

server.requestHandler(routeMatcher).listen(port,
                host, new Handler<AsyncResult<HttpServer>>() {
                    public void handle(AsyncResult<HttpServer> asyncResult) {
                        if (asyncResult.succeeded()) {
                            logger.info(s + ":  Started on " + host + ":"
                                    + port);
                        } else {
                            logger.info(s + ": Unable to start server.\n "
                                    + asyncResult.cause());
                        }
                    }
                });

您可能有一个问题什么是http选项类型请求处理程序的用途。答案是非常有趣的。 Javascript是一种安全的语言,不允许跨源Http请求。所以,允许跨源请求javascript发送选项类型请求每个http请求请求和检查天气CORS是否支持。在这样的Javascript命中服务器两次一个检查cors是否支持和一个fatch数据。

You may have a question What is the use of http options type request handler. The answer is for that is very interesting. Javascript is a secured language that do not allow Cross origin Http request. So, to allow cross origin request javascript send a options type request for each http request request and check weather CORS is supported or not. In such Javascript hits server two times one to check cors is supported or not and one to fatch data.

这篇关于如何使用Vert.x 2.x启用CORS的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆