1

React project
POST request by Fetch:

getResource = async () => {
const res = await fetch('https://fanml753mfuuq-uc.a.run.app/api/v1/login/access-token', {
    headers: {
        'Accept': 'application/json',
        'Content-Type': 'application/x-www-form-urlencoded',
        'Access-Control-Allow-Methods': 'GET, PUT, POST, DELETE, HEAD, OPTIONS'
        // 'Authorization': 'Bearer TOKEN',

    },
    method: 'POST',
    mode: 'no-cors',
    credentials: 'include',
    body: 'grant_type=&username=charl%40mavencodom&password=test&scope=&client_id=&client_secret='
});
// if (!res.ok) {
//     throw new Error(`Not Fetch, received ${res.status}`)
// }
const body = await res.json();
return body;

};

I get:

Unhandled Rejection (SyntaxError): Unexpected end of input.

If I uncomment 'if', then I get:

Not Fetch, received 0 .

The request status is 200, but there is no response.

API docs:

enter image description here

Update code with a try/catch and console.log the error

 let response;
    try {
        response = await fetch(
            'https://fan-foto-ml753mfuuq-uc.a.run.app/api/v1/login/access-token',
            {
                headers: {
                    'Accept': 'application/json',
                    'Content-Type': 'application/x-www-form-urlencoded',
                    // 'Authorization': 'Bearer TOKEN',

                },
                method: 'POST',
                mode: 'no-cors',
                // credentials: 'include',
                body: 'grant_type=&username=charles%40mavencode.com&password=test&scope=&client_id=&client_secret='
            });
    } catch (error) {
        console.log(error)
        // manage errors here
    }
    console.log(response);
    return response;

In the dev tools network tab

enter image description here

the expected results

{
  "access_token": "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjo1LCJleHAiOjE1OTA1Njk4NTYsInN1YiI6ImFjY2VzcyJ9.SVnzXxc_RMfFwTuzFuK3ul-Vahej_05NpdfPqdt34EY",
  "token_type": "bearer"
}
Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
your uncle
  • 43
  • 1
  • 1
  • 4
  • It looks like there could be an error happening, add a try/catch and console.log the error. Also adding `Access-Control-Allow-Methods': 'GET, PUT, POST, DELETE, HEAD, OPTIONS` on the client side will not help resolve CORS issues, that header needs to be on the response from the server. – Alexander Staroselsky May 27 '20 at 13:12
  • Alexander Staroselsky, I did it with try/catch and console.log the error. error is empty. response is ` Response {type: "opaque", url: "", redirected: false, status: 0, ok: false, …} body: (...) bodyUsed: false headers: Headers {} ok: false redirected: false status: 0 statusText: "" type: "opaque" url: "" __proto__: Response` – your uncle May 27 '20 at 13:39
  • Okay, I’d update your code to show that try catch. That being said, it’s not clear that the response is JSON, so executing the json() method could result in errors. In the dev tools network tab, what is the response content-type header? In that request do you see the expected results? – Alexander Staroselsky May 27 '20 at 14:03
  • I updated question – your uncle May 27 '20 at 14:14

1 Answers1

-1

You need to use a try/catch block to catch errors thrown by the fetch call ( a network error for example ).

getResource = async () => {
  let response;
  try {
    response = await fetch(
    'https://fanml753mfuuq-uc.a.run.app/api/v1/login/access-token',
    {
      headers: {
        'Accept': 'application/json',
        'Content-Type': 'application/x-www-form-urlencoded',
        'Access-Control-Allow-Methods': 'GET, PUT, POST, DELETE, HEAD, OPTIONS'
        // 'Authorization': 'Bearer TOKEN',

      },
      method: 'POST',
      mode: 'no-cors',
      credentials: 'include',
      body: 'grant_type=&username=charl%40mavencodom&password=test&scope=&client_id=&client_secret='
    });
  } catch( error ) {
    // manage errors here
  }
  return response;
}

  • `Response {type: "opaque", url: "", redirected: false, status: 0, ok: false, …} body: (...) bodyUsed: false headers: Headers {} ok: false redirected: false status: 0 statusText: "" type: "opaque" url: "" __proto__: Response` – your uncle May 27 '20 at 13:30
  • You are using 'no-cors', so you are getting an opaque response object. Check this: https://stackoverflow.com/questions/36292537/what-is-an-opaque-response-and-what-purpose-does-it-serve – crisisinaptica May 28 '20 at 14:28