Error when accessing API with fetch while setting mode to 'no-cors' [duplicate]

霸气de小男生 提交于 2019-12-20 07:23:51

问题


When trying to resolve a fetch promise with JS is set the mode to 'no-core' based on this answer. However setting the mode to 'corse' results in having:

Access to fetch at '{endpoint}' from origin 'http://localhost:3000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.

So I wrote this in my function:

search() {
    return fetch(`${baselink}${summonerEndpoint}${summoner}${apikey}`, {mode: 'no-cors'}).then(response => {
      return response.json()
    }).then(jsonResponse => {
      console.log(jsonResponse);
      if (!jsonResponse.info) {
        return [];
      }
      return jsonResponse.info.items.map(info => ({
        id: info.id,
        accountId: info.accountId,
        name: info.name,
        profileIconId: info.profileIconId,
        revisionDate: info.revisionDate,
        summonerLevel: info.summonerLevel
      }));
    });
  }

This results in following error Uncaught (in promise) SyntaxError: Unexpected end of input for return response.json(), but with no further message. What am I doing wrong?


回答1:


If an opaque response serves your needs

It doesn't. You want to see the response. You can't see an opaque response (that is what opaque response means).

no-cors mode means that if the browser has to do anything that requires permission from CORS, it will fail silently instead of throwing an error.

So it is silently failing to get the response, then trying to parse that nothing as JSON (which throws a different error).

You need:

  • To not use no-cors mode
  • The server to grant permission using CORS

See this question for more information about CORS in general.



来源:https://stackoverflow.com/questions/53442236/error-when-accessing-api-with-fetch-while-setting-mode-to-no-cors

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