我正在使用nickel.rs、PostgreSQL 和Angular.js。我可以使用 HTTP POST 插入到我的表中:
// insert
{
let conn = shared_connection.clone();
router.post("/api/movies", middleware! { |request, mut response|
let conn = conn.lock().unwrap();
let stmt = match conn.prepare("insert into movie (title, releaseYear, director, genre)
values ($1, $2, $3, $4)") {
Ok(stmt) => stmt,
Err(e) => {
return response.send(format!("Preparing query failed: {}", e));
}
};
let movie = request.json_as::<MovieInsert>().unwrap();
match stmt.execute(&[
&movie.title.to_string(),
&movie.releaseYear,
&movie.director.to_string(),
&movie.genre.to_string()
]) {
Ok(v) => println!("Inserting movie was Success."),
Err(e) => println!("Inserting movie failed. => {:?}", e),
};
// ERROR (1)
// return response.set(Location("/".into()));
});
}
我知道这很好用,因为该行已插入 PostgreSQL 表中。但是,Chrome 网络浏览器显示错误:
POST http://localhost:6767/api/movies 404 (Not Found)
ERROR (1)
我还在线添加了代码
response.set(Location("/".into()));
但是,控制台显示错误。
expected `core::result::Result<nickel::middleware::Action<nickel::response::Response<'mw, _>, nickel::response::Response<'mw, _, hyper::net::Streaming>>, nickel::nickel_error::NickelError<'mw, _>>`,
found `&mut nickel::response::Response<'_, _>`
(expected enum `core::result::Result`,
found &-ptr)
现在是我的代码应用了 Shepmaster 所说的。
// insert
{
let conn = shared_connection.clone();
router.post("/api/movies", middleware! { |request, mut response|
let conn = conn.lock().unwrap();
let stmt = match conn.prepare("insert into movie (title, releaseYear, director, genre)
values ($1, $2, $3, $4)") {
Ok(stmt) => stmt,
Err(e) => {
return response.send(format!("Preparing query failed: {}", e));
}
};
let movie = request.json_as::<MovieInsert>().unwrap();
match stmt.execute(&[
&movie.title.to_string(),
&movie.releaseYear,
&movie.director.to_string(),
&movie.genre.to_string()
]) {
Ok(v) => println!("Inserting movie was Success."),
Err(e) => println!("Inserting movie failed. => {:?}", e),
};
response.set(StatusCode::PermanentRedirect)
.set(Location("/".into()));
""
});
}
但发生了错误。
src/main.rs:155:18: 155:43 错误:该特征modifier::Modifier<nickel::response::Response<'_, _>>
未针对类型hyper::header::common::location::Location
[E0277] src/main.rs:155 .set(Location("/".into()));
最后我像这样修复!
Ok(v) => {
println!("Inserting movie was Success.");
response.set(StatusCode::Ok);
},
Err(e) => println!("Inserting movie failed. => {:?}", e),
};
//response.set(StatusCode::PermanentRedirect)
// .set(Location("/".into()));
//""
return response.send("");