0

I am trying to fetch some data from an external API with NextJS. I have tested the API url with postman and it works fine - result is fetched properly. But when I try to fetch API data with fetch() method in NextJS it gives me net::ERR_ABORTED 400 error in the browser console.

Here is piece of code:

React component:

import {fetchApiProduct} from "../../../lib/content-api";

export default function ProductPage(params) {
  const product = fetchApiProduct();

  return (
    <>
      <h3>product.name</h3>
    </>
  );
}

fetachApiProduct() method:

export async function fetchApiProduct() {
  const sku = await useRouter().query.sku;
  const url = `https://sometesturl/api/product/${sku}`;
  console.log(url);

  const res = await fetch(url, {
    method: 'GET',
    mode: 'no-cors',
    headers: {
      'Accept': 'application/json'
    }
  })

  console.log(res);
  return res;
}

Edit:

If I use only:

await fetch(url);

Then this is what I get in console:

  1. Access to fetch at '...' 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.
  2. net::ERR_FAILED
  3. Uncaught (in promise) TypeError: Failed to fetch
Phil
  • 157,677
  • 23
  • 242
  • 245
Denis2310
  • 939
  • 1
  • 15
  • 41
  • 2
    Do you know what `mode: 'no-cors'` does? If you did, you would not be using it. I don't blame you if you added it because of the error message though, it's **very** confusing and IMO should be changed – Phil Jun 30 '21 at 09:09
  • 1
    Try just `const res = await fetch(url)` (also, I'm pretty sure `product` is a Promise, not the actual product) Plus, the API needs to support CORS, or your website cannot use it client-side, period. –  Jun 30 '21 at 09:09
  • I dont know real purpose fo 'no-cors' but if I use only await fetch(url), then this is what I get in console: Access to fetch at '...' 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., and right after that: Uncaught (in promise) TypeError: Failed to fetch – Denis2310 Jun 30 '21 at 09:12
  • Yep, that's the error message I was referring to. FYI an _"opaque response"_ **NEVER** serves your needs (unless you're creating a service worker) – Phil Jun 30 '21 at 09:13
  • I am totally new to react and nextjs so this everything confuses me – Denis2310 Jun 30 '21 at 09:16
  • 1
    TL:DR - JS that runs in the browser can only access other domains if that domain says you can – Phil Jun 30 '21 at 09:20

0 Answers0