How do you add CORS headers in Redstone interceptor?

∥☆過路亽.° 提交于 2019-12-20 03:04:24

问题


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();
    }
}

回答1:


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() 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.



来源:https://stackoverflow.com/questions/28749814/how-do-you-add-cors-headers-in-redstone-interceptor

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!