2

my JS and HTML is at below, when I enter this URL: http://localhost:8080/api/languages/getall in Chrome, it returns [{"id":1,"name":"c"},{"id":2,"name":"java"}],
but the code at below is not working, it might be the root caused and how to fix it?

    $.ajax({
    url: "http://localhost:8080/api/languages/getall",
    type: 'GET',
    dataType: 'json', // json?
    CORS: true ,
    contentType:'application/json',
    headers: {
        'Access-Control-Allow-Origin': '*',
    },
    success: function (data){
        console.log(data);
    }
});

html

<!DOCTYPE html>
<html>
    <head>
        <title>How to consume RESTful Web Service using jQuery</title>
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
        <script src="js/consume-rest.js"></script>
    </head>
    <body>
        <div>
            <h3>How to consume RESTful Web Service using jQuery</h3>

            <p id="id">ID: </p>
            <p id="content">Content: </p>

        </div>
    </body>
</html>

spring

  @CrossOrigin(origins = "http://localhost:8080")
  @GetMapping("/languages/getall")
  List<GetLanguageResponse>getAllResponse(){
    return languagesService.getAllResponse();
  }//it returns array of object

https://pasteboard.co/KZ7BZqMSh7yX.png the link shows the answer of backend server it works.And i also added cross origin above the code .Error is still same,"from origin 'null' has been blocked by CORS policy" and "jquery.min.js:2 GET http://localhost:8080/api/languages/getall net::ERR_FAILED"

Just to let yall know in my react code it works

const App = () => {

  const [groups, setGroups] = useState([]);
  const [loading, setLoading] = useState(false);

  useEffect(() => {
    setLoading(true);

    fetch('api/languages/getall')
      .then(response => response.json())
      .then(data => {
        setGroups(data);
        setLoading(false);
      })
  }, []);

  if (loading) {
    return <p>Loading...</p>;
  }

  return (
    <div className="App">
      <header className="App-header">
        <img src={logo} className="App-logo" alt="logo" />
        <div className="App-intro">
          <h2>JUG List</h2>
          {groups.map(group =>
            <div key={group.id}>
              {group.name}
            </div>
          )}
        </div>
      </header>
    </div>
  );
}

1 Answer 1

1

First thing we could say is that your API apparently returns an array of objects, while you're trying to use data as an object directly. Also, did you try to console.log(data) in order to see what happens ? I guess your error catcher is never triggered ?

Did you try with these options ?

$.ajax({
    url: "http://localhost:8080/api/languages/getall",
    type: 'GET',
    dataType: 'jsonp', // json?
    CORS: true ,
    contentType:'application/json',
    headers: {
        'Access-Control-Allow-Origin': '*',
    },
    success: function (data){
        console.log(data);
    }
});

Also, make sure your backend sends a 2xx response and configure your CORS on the back-end side.

Sign up to request clarification or add additional context in comments.

6 Comments

Access to XMLHttpRequest at 'localhost:8080/api/languages/getall' from origin 'null' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. localhost:8080/api/languages/getall:1 Failed to load resource: net::ERR_FAILED console.log(data) VM29:1 Uncaught ReferenceError: data is not defined at <anonymous>:1:13
i just realized ur right it is because i have no experience in eihter js or jquery ,how should my code be?And is it best practice to use jquery for this kinda purposes like web app.Thanks in advance for your answers
Try adding this header at the same level as your url for instance "headers": { "accept": "application/json", "Access-Control-Allow-Origin":"*"} Obviously it's not recommended to let the origin be ''. You should use your origin, which is localhost in that case, or your production URL. If your API is public, I believe '' is fine, it looks like this is the case :-)
yes it is public i added your code but it still gives the same error
Did you try with dataType: "json" or jsonp as well (jsonp is used for cross domain requests, but it looks like you're on the same domain? If it's a cross-domain request, you may need jsonpCallback too) ?
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.