Question:
How to solve the VueJS API error in production mode (npm run build)?

Problem

I'm building 2 applications that transfer data through an API. It works perfectly until I use npm run build. The strange thing is, I get an error (Failed to load resource: the server responded with a status of 404 (Not Found)) and my screen freezes for 30 seconds when I'm on the page that makes the request, but when I visit the API URL everything seems to work perfectly.


Using CORS browser extension, but no result.


function in vue component:


fetchData() {

      console.log('fetching', import.meta.env.VITE_APP_ROOT_URL_TO_API + '/checklist/' + this.name);

      axios.get(import.meta.env.VITE_APP_ROOT_URL_TO_API + '/checklist/' + this.name)

          .then((response) => {

            console.log(response.data);

            this.data = response.data;


            if (this.name === 'klusjes binnen' || this.name === 'klusjes buiten') {

              this.activeAccordion = this.filteredCheckListItems.length;

              this.klusjes = true;

            }

          })

    },


.env:


VITE_APP_ROOT_URL_TO_API=http://mcdo-app-desktop.test/api


PHP function it directs to:

public function singleChecklist($name) {

        $checkList = Checklist::where('name', $name)->with('checklistItem', 'checklistItem.listItem')->first();


        $checkList->checklistItem->each(function ($list) {


            $options = [

                "ssl" => [

                    "verify_peer"=>false,

                    "verify_peer_name"=>false,

                ]

            ];


            $list->image = base64_encode(file_get_contents(url('/') . '/storage/images/' . $list->icon_url,  false, stream_context_create($options)));

        });

        return response()->json($checkList);

    }


Solution

Given that the API works perfectly when you visit the URL directly, but it fails when you build and run the application, it might indicate that there is an issue with how you're handling the environment variables in your Vue.js application.


I suggest looking in the network tab for the request that's causing the 404 error and inspecting the URL. You also need to add a catch statement to capture any errors that may occur during the request.


My guess would be that import.meta.env.VITE_APP_ROOT_URL_TO_API + '/checklist/' + this. name is not a valid URL.


Suggested blog

>Create a project using Vue.js: Beginners Guide

>Authentication with Vue 3 and Firebase

>Plugins and Presets for Vuejs project

>Create a Vue.js application with CLI Services

>Create a project using Vue.js: Beginners Guide

>Create Vue.js application API


Nisha Patel

Nisha Patel

Submit
0 Answers