React: Call to external API from localhost using axios not working

Viewed 180

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.

1 Answers

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

Related