Unable to set headers on Response
jpettersson opened this issue · comments
Hi,
I'm trying to set headers based on the enable_cors.rs
example, but I run into a type error. I've tried various combinations of rustc, hyper and nickel versions, but they all yield the same error:
src/main.rs:13:13: 13:16 error: the trait bound `hyper::header::AccessControlAllowOrigin: modifier::Modifier<nickel::Response<'_>>` is not satisfied [E0277]
src/main.rs:13 res.set(AccessControlAllowOrigin::Any);
My implementation looks like this:
#[macro_use] extern crate nickel;
extern crate hyper;
extern crate rustc_serialize;
use nickel::{Nickel, HttpRouter, Request, Response, MiddlewareResult};
use hyper::header::{AccessControlAllowOrigin, AccessControlAllowHeaders, Location};
use rustc_serialize::json::{ToJson};
fn main() {
let mut server = Nickel::new();
fn enable_cors<'mw>(_req: &mut Request, mut res: Response<'mw>) -> MiddlewareResult<'mw> {
res.set(AccessControlAllowOrigin::Any);
res.next_middleware()
}
server.utilize(enable_cors);
server.get("/v0/graphs", middleware!{ |_|
"hello".to_string().to_json()
});
server.listen("127.0.0.1:6767");
}
Dependencies:
[dependencies]
nickel = "0.8.1"
rustc-serialize = "0.3.19"
[dependencies.hyper]
version = "0.9"
default-features = false
I'm guessing I've missed something obvious.. any ideas?
Thanks!
I found an old issue which describes the same problem: #221
Seems it's a Cargo dependency resolution issue. I managed to work around it for now by setting raw headers like this:
res.headers_mut().set_raw("Access-Control-Allow-Origin", vec![b"*".to_vec()]);
res.headers_mut().set_raw("Access-Control-Allow-Headers", vec![b"Origin X-Requested-With Content-Type Accept".to_vec()]);
It seems in my project I had to import hyper::header::Headers as well as the actual header. Does that make any difference?
You can see a working example in #426
Closing as we now have a working CORS example. Please re-open if there are still issues.