-1

I am trying to fetch data from API using JavaScript and this API is working in Postman but not working in JavaScript.

This code show in console as failed to fetch response data and undefined:

<!DOCTYPE html>
<html>
<head>
    <meta charset="ISO-8859-1">
    <title>Insert title here</title>
</head>
<body>
    <h2> only fetch APi</h2>

    <script>
    fetch('https://smweb.in/hungaroo/app/api/plan_list', {
        method: 'POST',
        mode: 'no-cors',
        redirect: 'follow',
        headers: {
            "Accept": "application/json",
            "Access-Control-Allow-Origin": "*",
            "Content-Type": "application/json"
        }
    })
    .then(function (response) {
        return response.text();
    })
    .then(function(data) {
        console.log(data);
    })
    </script>
</body>
</html>
Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
supriya
  • 1
  • 3

1 Answers1

1

It seems that this code yields in an opaque response (using the request mode: 'no-cors'). Opaque responses don't have a body, and hence you get nothing when trying to log the response. Access-Control-Allow-Origin is a response header, so it should be set in the response object sent by the origin(server), not in the request. Without this, you will not get a meaningful response from the server. Adding mode:'no-cors' to your request is a hacky way to get an opaque response from an endpoint which does not have Access-Control-Allow-Origin set in the response header. Further explanation here:

Trying to use fetch and pass in mode: no-cors

how to process fetch response from an 'opaque' type?

Why Postman works then? I found this article useful: https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS

It seems that while the Fetch API follows same-origin policy, Postman doesn't.

david_25
  • 55
  • 1
  • 7