No 'Access-Control-Allow-Origin' header when receiving JSON data from server

六眼飞鱼酱① 提交于 2020-01-11 14:12:23

问题


I am trying to make the client side receiving JSON data from the Server, however, it constantly popped up the error method. When I try to use Chrome to debug, it popped up: 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.

I have tried to change dataType to 'jsonp', but it doesn't work. However, when I use POSTMAN to test the data from Server, everything works fine, I can see the JSON data comes from the server.

Here is the picture shows the testing result from POSTMAN: Pictures shows POSTMAN testing result from server

The following is my code on both server side and client side: Could anyone tell me how to add the 'Access-Control-Allow-Origin' header for my java code?(if it is this problem)

The Java Code:

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

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

来源:https://stackoverflow.com/questions/33572801/no-access-control-allow-origin-header-when-receiving-json-data-from-server

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!