我正在努力使用AJAX从Rust Hyper Server获得JSON响应。这是Rust代码。
extern crate hyper;
extern crate futures;
#[macro_use]
extern crate serde_json;
use hyper::{Body, Response, Server, Method, StatusCode};
use hyper::service::service_fn_ok;
use futures::Future;
fn main() {
let router = || {
service_fn_ok(|req| {
match(req.method(), req.uri().path()) {
(&Method::GET, "/") => {
Response::new(
Body::from(
json!([{
"id": "01",
"Name": "faheem"
},
{
"id": "02",
"Name": "waseem"
}]).to_string()
)
)
},
(_, _) => {
let mut res = Response::new(Body::from("not found"));
*res.status_mut() = StatusCode::NOT_FOUND;
res
}
}
})
};
let addr = "127.0.0.1:3000".parse().unwrap();
let server = Server::bind(&addr).serve(router);
hyper::rt::run(server.map_err(|e| {
eprintln!("server error: {}", e);
}));
}
Ajax代码。这段代码可以很好地与NodeJS服务器一起使用。通过仅在中间件中添加 header Access-Control-Allow-Origin。但是,在rust hyper环境中,我可以找到任何有助于在Hyper服务器环境中添加Access-Control-Allow-Origin的文档。
<script>
$(document).ready(function () {
BindTable();
$("#btnSend").click(function () {
$.ajax({
crossDomain: true,
url: "http://localhost:3000/add",
type: "POST",
contentType: 'application/json',
data: JSON.stringify({
'student': $('#student').val(),
}),
success: function(data){
console.log(data);
$("#tbDetails").text("");
BindTable();
}
});
});
});
function BindTable()
{
$.ajax({
type: 'GET',
async: false,
headers: {
'Access-Control-Allow-Origin': 'http://localhost:3000/'
},
crossDomain: true,
url: "http://localhost:3000/",
contentType: "application/json",
dataType: "json",
success: function (msg) {
console.log(msg);
$.each(msg, function (index) {
var row = '<tr><td> ' + msg[index].id + ' </td> <td> ' + msg[index].name + ' </td></tr>';
$("#tbDetails").append(row);
});
}
});
}
</script>
<label for="student">Add student</label>
<input id="student" name="student" type="text" value="" />
<input id="btnSend" type="button" value="Send" />
<table id="tbDetails" border="1" cellpadding="2">
<tr>
<td>ID</td> <td>Name</td>
</tr>
<tbody>
</tbody>
</table>
错误
最佳答案
您应该在托管服务器的HTTPResponse设置中添加Access-Control-Allow-Header条目。此外,在Ajax请求中的代码中, header 值在http后被注释。用双引号关闭该条目。
关于ajax - 关于Ajax GET请求的Rust Hyper CORS Policy错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60596160/