1

I'm working on a simple CRUD app with Nextjs. The app is currently local, not deployed anywhere yet. I'm trying to make an API call to an external API:

import axios from "axios";

let headers = {
    "token": process.env.NEXT_PUBLIC_BARCODELOOKUP_API_KEY,
};

export const getRecordInfoByBarcode = async (barcode) => {

    const searchByBarcode = `https://api.barcodelookup.com/v3/products?upc=${barcode}&formatted=y`;

    if (barcode === "" || barcode === undefined) {
        throw "Barcode cannot be empty!";
    }

    const res = await axios.get(searchByBarcode, { headers })
        .then(response => {
            console.log("response from barcodelookup");
            console.log(response);
        })
        .catch(e => console.log(e))
}

but I'm getting the following error:

Access to XMLHttpRequest at 'https://api.barcodelookup.com/v3/products?upc=724381033210&formatted=y' from origin 'http://localhost:3001' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.

According to the API's documentation (https://devapi.barcodespider.com/documentation) you can either send the token in the header or as part of the URL: https://api.barcodelookup.com/v3/products?token=XXXXXXXXXXXXXXXXXX&upc=029667003315

I've tried both ways and none worked. Also tried the same call from my backend app (which is written in Go) but I'm getting the same results.

I can perform the call from a REST client such as POSTMAN.

The API docs do not offer a way to register my app.

MrCujo
  • 1,218
  • 3
  • 31
  • 56
  • That's a CORS issue, see [How does Access-Control-Allow-Origin header work?](https://stackoverflow.com/questions/10636611/how-does-access-control-allow-origin-header-work). If you don't have control over the external API to enable CORS, then your only option is to proxy the request (you can use Next.js API routes or rewrites, see [NextJs CORS issue](https://stackoverflow.com/questions/65058598/nextjs-cors-issue)) and circumvent CORS altogether. – juliomalves Jun 26 '22 at 15:14

1 Answers1

0

Have you tried logging process.env.NEXT_PUBLIC_BARCODELOOKUP_API_KEY to the console? If you have created your app using Create React App then you need to prefix the environment variables with REACT_APP like REACT_APP_NEXT_PUBLIC_BARCODELOOKUP_API_KEY

JaswanthSriram
  • 194
  • 1
  • 8
  • the problem is not the token. The token is being retrieved correctly. The problem is the actual request. From Postman the same request works fine but from my app the request returns a 403. – MrCujo Jun 24 '22 at 22:46