如何在Redstone拦截器中添加CORS头? [英] How do you add CORS headers in Redstone interceptor?

查看:126
本文介绍了如何在Redstone拦截器中添加CORS头?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想为收到的请求添加CORS标头,但我注意到 app.response.headers 是一个不可变的地图和应用程序.request.response 不存在,即使它出现在文档示例中。所以,对 OPTIONS 请求我使用一个新的 Shelf 响应,但我找不到一种方式以向实际请求的响应中添加任何新标头。任何想法?

I'm trying to add CORS headers to incoming requests but I've noticed that app.response.headers is an immutable map and app.request.response doesn't exist even though it appears in the documentation examples. So, to the OPTIONS request I'm replying using a new Shelf response, but I can't find a way to add any new headers to the response of the actual request. Any ideas?

@app.Interceptor(r"/api/.*", chainIdx: 1)
corsInterceptor() {

    if (app.request.method == "OPTIONS") {
        var response = new shelf.Response.ok("", headers: HEADERS);
        app.chain.interrupt(statusCode: HttpStatus.OK, responseValue: response);
    } else {
    // app.request.response is not available
        app.request.response.headers.add('Access-Control-Allow-Origin', '*');
        app.chain.next();
    }
}


推荐答案

I发现Interceptor文档中第一段代码的修复...:)

I found the fix in the first piece of code inside the Interceptor documentation...:)

@app.Interceptor(r"/api/.*", chainIdx: 1)
corsInterceptor() {
    if (app.request.method == "OPTIONS") {
        var response = new shelf.Response.ok("", headers: HEADERS);
        app.chain.interrupt(statusCode: HttpStatus.OK, responseValue: response);
    } else {
        app.chain.next(() => app.response.change(headers: HEADERS));
    }
}

app.chain.next ()可以接受一个回调作为参数,期望返回一个 Response 对象。在这种情况下, app.response.change()返回带有正确标头的响应。

app.chain.next() can take a callback as argument, which is expected to return a Response object. In this case app.response.change() returns a response with the correct headers.

这篇关于如何在Redstone拦截器中添加CORS头?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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