Rust Hyper CORS Policy error on Ajax GET request

Viewed 549

I am working to get the JSON response from the Rust Hyper Server using the AJAX. Here is the Rust code.

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

The Ajax code. This code is working fine and well with NodeJS server. By just adding the header Access-Control-Allow-Origin in the middle ware. But, in the rust hyper environment I could find any documentation which will help to add the Access-Control-Allow-Origin in the Server environment of Hyper.

<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>

The error

enter image description here

1 Answers

You should add Access-Control-Allow-Header entry in the HTTPResponse settings of the server you have hosted. Further in your code in Ajax request the header value is commented after http. Close this entry in double quotation.

Related