No' Access-Control-Allow-Origin'从服务器接收JSON数据时的标头

时间:2015-11-06 17:56:01

标签: javascript java json xmlhttprequest

我试图让客户端从服务器接收JSON数据,但是,它不断地弹出错误方法。当我尝试使用Chrome进行调试时,会弹出:XMLHttpRequest cannot load http://localhost:8080/TransportationNetwork/rest/paths?st=3,6. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access.

我尝试将dataType更改为' jsonp',但它不起作用。但是,当我使用POSTMAN来测试来自Server的数据时,一切正常,我可以看到JSON数据来自服务器。

下图显示了POSTMAN的测试结果: Pictures shows POSTMAN testing result from server

以下是我在服务器端和客户端的代码:  谁能告诉我如何添加' Access-Control-Allow-Origin'我的java代码的标题?(如果是这个问题)

Java代码:

@Path("/paths")
public class PathsResource {
    PathDao pathDao;

public PathsResource() {
    pathDao = new PathDao();
}

@GET
@Produces(MediaType.APPLICATION_JSON)
//@Consumes("text/plain")
public List<DirectedEdge> pathsInfo(@QueryParam("st") String st) {
    System.out.println("Searching paths : " + st);
    return pathDao.getEdgeList(st);
}  
}

Javascript:

var serviceURL = "http://localhost:8080/TransportationNetwork/rest/paths";


$('#findPaths').click(function() {
        getPaths();
});

function getPaths() {
    console.log('display paths');
    $.ajax({
        type:'GET',
        url: serviceURL,
        dataType:'json', // data type get back from server
        data:'st=' + dataToServer(), //data sent to server 
        success: renderList,
        error: function(jqXHR, textStatus, errorThrown){
            alert('Path Finder: ' + textStatus);
        }
    });
}

function dataToServer() {
    var array = "";
        str1 = $('#source').val();
        str2 = $('#target').val();

    array = str1 + "," + str2;

    return array;
}

function renderList(data) {
    //var parsedData = JSON.parse(data); 
    var list = data == null ? [] : (data instanceof Array ? data : [data]);
    $('#PathList li').remove();
    $.each(list, function(index, path) {
        $('#PathList').append('<li>'+ path.source + ' -> ' + path.target + ': ' + path.weight + '</li>');
    });
}

0 个答案:

没有答案