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:
- 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.
- net::ERR_FAILED
- Uncaught (in promise) TypeError: Failed to fetch