ajax - 关于Ajax GET请求的Rust Hyper CORS Policy错误

标签 ajax rust hyper

我正在努力使用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>

错误

enter image description here

最佳答案

您应该在托管服务器的HTTPResponse设置中添加Access-Control-Allow-Header条目。此外,在Ajax请求中的代码中, header 值在http后被注释。用双引号关闭该条目。

关于ajax - 关于Ajax GET请求的Rust Hyper CORS Policy错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60596160/

相关文章:

rust - 为什么 Rust Closure 在被调用之前就拥有所有权

rust - 无法构建 Hyper - crate 名称中的无效字符 `-`

multithreading - 我如何从另一个线程使用 hyper::client?

rust - 如何通过读取和转换文件来创建Stream?

rust - 如果文件不存在,有没有办法创建和打开文件,否则会失败?

php - 使用 AJAX 启动和停止 php 文件

php - 从文件中使用 php 和 ajax 进行分页

javascript - 使用引导代码点火器将数据从 Controller 发送到弹出模式

javascript - IE 上的 jQuery 脚本访问被拒绝

path - 我可以使用 `std::path::Path` 的 `strip_prefix` 来替换动态前缀吗?