Retrieving information from an API functions efficiently on a local environment but encounters issues when deployed

Having just embarked on my first adventure in creating a website with Nuxt.js, I've encountered an issue when trying to fetch data from an API. Everything seems to work perfectly fine locally, but once the site is hosted on Netlify, none of the code appears to be running. It seems like my lack of understanding of how static sites function might be causing this problem.

My goal is to implement a feature that checks for a browser cookie. If there isn't one, I aim to create it and then retrieve the user's general location using the API. The next step involves comparing their city against a predefined array of cities in New York. If there's a match, I want to close the banner displayed on the page. If a browser cookie already exists, the banner should remain closed.

Below is an abridged version of index.vue:

<template>
    <v-app v-bind:class="{ alertOpen: alertOpen }">
        <v-main>
            <v-banner
                class="state-alert"
                transition="slide-y-transition"
                v-bind:class="{ alertOpen: alertOpen }"
            >
                By our calculations, it looks like you might be visiting our website from outside of New York. Unfortunately at this time, we can't sell our Granola outside of New York. If you are buying a gift for someone with a New York address then please proceed.
                <template>
                    <v-btn
                        icon
                        color="alert"
                        v-on:click="alertOpen = false"
                    >
                        <v-icon>mdi-close</v-icon>
                    </v-btn>
                </template>
            </v-banner>
        </v-main>
    </v-app>
</template>

<script>
    let nyList = ['Albany', 'Amsterdam', 'Auburn', 'Batavia', 'Beacon', 'Binghamton', 'Buffalo', 'Canandaigua', 'Cohoes', 'Corning', 'Cortland', 'Dunkirk', 'Elmira', 'Fulton', 'Geneva', 'Glen Cove', 'Glens Falls', 'Gloversville', 'Hornell', 'Hudson', 'Ithaca', 'Jamestown', 'Johnstown', 'Kingston', 'Lackawanna', 'Little Falls', 'Lockport', 'Long Beach', 'Mechanicville', 'Middletown', 'Mount Vernon', 'New Rochelle', 'New York', 'Newburgh', 'Niagara Falls', 'North Tonawanda', 'Norwich', 'Ogdensburg', 'Olean', 'Oneida', 'Oneonta', 'Oswego', 'Peekskill', 'Plattsburgh', 'Port Jervis', 'Poughkeepsie', 'Rensselaer', 'Rochester', 'Rome', 'Rye', 'Salamanca', 'Saratoga Springs', 'Schenectady', 'Sherrill', 'Syracuse', 'Tonawanda', 'Troy', 'Utica', 'Watertown', 'Watervliet', 'White Plains', 'Yonkers'];

    export default ({
        head() {
            return {
                script: [{
                    body: true
                }]
            }
        },
        data() {
            return {
                geoData: [],
                alertOpen: true
            }
        },
        async fetch() {
            const locationCookie = this.$cookies.get('location-cookie');

            if(!locationCookie) {
                console.log('no cookie');
                this.$cookies.set('location-cookie', 'true', {
                    path: '/',
                    maxAge: 31556952
                });
                this.geoData = await fetch(
                    'https://ipgeolocation.abstractapi.com/v1/?api_key=1eef312cdda9428cac26815c9d3bdd26'
...

If you require additional information, here's the nuxt.config.js file:

export default {
    mode: "universal",

    // Global page headers (https://go.nuxtjs.dev/config-head)
    head: {
        title: 'homemade-crunch',
        meta: [
            { charset: 'utf-8' },
            { name: 'viewport', content: 'width=device-width, initial-scale=1' },
            { hid: 'description', name: 'description', content: '' }
        ],
        link: [
            { rel: "preconnect", href: "https://app.snipcart.com" },
            { rel: "preconnect", href: "https://cdn.snipcart.com" },
            { rel: 'stylesheet', href: 'https://cdn.snipcart.com/themes/...
...

The GitHub repository: https://github.com/mat148/Homemade-crunch and the live site:

If there's anything important I've missed or if any mistakes have been made, please feel free to point them out. Any assistance would be incredibly appreciated. Thank you!

Answer №1

After careful consideration, I made the choice to transfer my logic from the index.vue file to a separate JavaScript document.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Tips for storing a single document in two separate collections within the same MongoDB database

I am currently exploring nestjs and I am faced with a challenge. My goal is to retrieve a document from collection_1 and then store the same document into collection_2. I have tried using the $out aggregation, but found that I am only able to save one docu ...

The Laravel Ajax Request is Returning Null

I am faced with a perplexing issue involving a toggle button that should change the status (Show/Hide). Despite sending valid data via ajax and seeing correct data in the console, the request appears empty in the controller. I've made sure to include ...

I am looking to host several iterations of jQuery on a content delivery network within my Nuxt application

Currently, we are loading jQuery 3.1.4 externally from a CDN on the top page. index.vue head: { bodyAttrs: { id: 'overview' }, script: [ { src: 'https://cdnjs.cloudflare.com/ajax/libs/jquery/3.4.1/jquery.min ...

What is the best way to apply one JavaScript code to two separate HTML elements?

I am currently experiencing an issue where only the first mp4 file is working properly, while the second one does not. I am considering removing the stylesheet part as it is proving to be difficult for me to handle. I lack the skills to implement other sol ...

Can you provide guidance on invoking JavaScript from a dynamically generated textbox within an ASP.NET application?

// Adding Context-Menu to Control $(function () { var txt1 = "#" + "<%= **myCal**.ClientID %>"; // Linking Context-Menu to Control $(txt1).contextMenu(ctxtMenu, { theme: 'vista' }); }); Code behind ...

Hide all div elements except one by toggling them at the same position

I’m diving into the world of jQuery and facing some challenges with the .toggle() function. My goal is to have multiple <div> elements displayed in the same position, but only one visible at a time. When a new <div> is opened, the previous o ...

"Implementing class changes based on screen size using javascript is not functioning as expected

var d = document.getElementById('promo5'); var viewportWidth = window.innerWidth; function mobileViewUpdate() { if (viewportWidth <= 700) { d.className += (" .promo5-mobile"); } else if (viewportWidth >= 700) { d ...

Put dashes in the middle of each MongoDB post title

In my express app, users can create and view posts. Currently, I search for posts by their title. However, I am encountering an issue when the post title contains spaces. The search function works perfectly for titles without spaces, but it gives an error ...

The function getElementsByTagName() returned an undefined value at index [0]

I'm delving into AJAX for the first time and encountering an error. I've seen similar issues posted by others, but none of the solutions I found seem to apply to my code. The specific problem I'm facing is that rf.getElementsByTagName("motd ...

Python script utilizing Selenium to load only JavaScript content and excluding full HTML rendering

As I navigate through the link , I am on the lookout for the search bar marked with the class "search-field". The HTML snippet in question is as follows: from selenium import webdriver import time driver = webdriver.Firefox() driver.get("https://www.takea ...

Discord.js unable to locate a non-existent folder

I am currently developing a Discord Bot using Discord.js, and I have a feature that sends a random image from a pre-defined set. Here's the code snippet: client.on('message', msg => { if (msg.content === 'I Hate It'){ ...

MongoDB effortlessly integrates arrays into data schemas

I find myself in a puzzling situation without knowing the cause. Despite my efforts, I cannot seem to find any information on this strange issue. Therefore, I have turned to seek help here. //mongoDB data schema const dataSchema = mongoose.Schema({ use ...

react-responsive-carousel: setting a specific height for thumbnail images

After setting a fixed height for the image, I noticed that the same height is also being applied to the thumbnails. How can I avoid this issue? <Carousel width="600px" dynamicHeight={false}> {data?.book?.images.map((image, i) => ( ...

Adjust the size of the image to perfectly fit within the div without enlarging it

I have a variety of images with different dimensions, ranging from 50x100 to 4000x4000 pixels. My objective is to display these images in their original size or scale them down to fit within the browser window. However, I have encountered an issue where t ...

Using Vue.js to update the v-bind:style when the mouse hovers over the element

I am working with a span element that displays different background images based on certain conditions. Here is the HTML: <span v-if="type" :style="styles" > </span> In the computed properties section: ...

Encountering issues with retrieving the id from the chosen values in a multi-select list box using AngularJS

After successfully moving items from one list box to another, the next step is to save the list of all items in the second list box along with their respective ids into the database. However, there seems to be an issue with retrieving the ids from the seco ...

Arrange and display similar objects together

I have a list of items in a listView that need to be visually grouped based on their class, displayed within boxes. For example, I have 5 items with the following classes: <div class="1"></div> <div class="1"></div> <div class= ...

Tips for transforming a JSON array retrieved from a REST API into a usable object

Upon receiving a message from my backend, it appears as follows: [ [ { "id": 1, "date": "2018-12-31" }, { "id": 12, "standard": null, "capacity": 7, "descr ...

What is the method to have VIM recognize backticks as quotes?

Currently working in TypeScript, I am hoping to utilize commands such as ciq for modifying the inner content of a template literal. However, it appears that the q component of the command only recognizes single and double quotation marks as acceptable ch ...

Create a unique filter in an ng-repeat directive that allows users to personalize the data displayed

Is there a way to create a custom filter that hides the inventory column for Color Pencil Special on October 2nd, 2017 in the view? The inventory for Color Pencil Special is dependent on the inventory of regular Color Pencils, which are stored somewhere e ...