Home  >  Article  >  Web Front-end  >  ## Why am I getting a SyntaxError when using fetch API with \'no-cors\' mode despite expecting an opaque response?

## Why am I getting a SyntaxError when using fetch API with \'no-cors\' mode despite expecting an opaque response?

Linda Hamilton
Linda HamiltonOriginal
2024-10-25 22:44:29557browse

## Why am I getting a SyntaxError when using fetch API with 'no-cors' mode despite expecting an opaque response?

Fetch API Error in 'no-cors' Mode Despite Opaque Response Expectation

Issue: An attempt to fetch an API with the mode set to 'no-cors' results in a SyntaxError in response to response.json().

Explanation:

When using the fetch API with 'no-cors' mode, the browser will silently fail any requests that require CORS permission. The error message "Unexpected end of input" is thrown because the fetch operation returns an opaque response (meaning its contents cannot be accessed).

Solution:

The "if an opaque response serves your needs" indicates that the server does not grant CORS permission to the request. To resolve the issue, you should:

  • Remove 'no-cors' mode: Set the mode to 'cors' or omit it entirely.
  • Configure the server to grant CORS permission: Add the appropriate CORS headers to the server's response, such as 'Access-Control-Allow-Origin: *' for all origins or 'Access-Control-Allow-Origin: https://mysite.com' for specific origins.

Additional Note:

CORS (Cross-Origin Resource Sharing) protects against cross-site scripting (XSS) attacks by preventing unauthorized access to resources from different origins. Granting CORS permission should be done carefully to maintain security.

Reference:

  • [CORS in General](https://stackoverflow.com/questions/6359744/what-is-cross-origin-resource-sharing-cors)

The above is the detailed content of ## Why am I getting a SyntaxError when using fetch API with \'no-cors\' mode despite expecting an opaque response?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn