How can I troubleshoot the issue with my browser not connecting through the proxy with NuxtJS and Axios

While server rendering is functioning as expected with the proxy, a discrepancy arises when the request is made from the browser. In server-side rendering, the request goes to custom-server.com/v1/places, whereas in the browser it goes to current-domain.com/api/places.

Why does this issue occur only when requesting from the browser? Is the proxy functionality limited to the server side? Any assistance on resolving this would be highly appreciated.

Reviewing my NuxtJS configuration:

require('dotenv').config();

export default {
    mode: 'universal',
    buildModules: [],
    modules: [
        '@nuxtjs/axios',
        '@nuxtjs/proxy',
        ['@nuxtjs/dotenv', { systemvars: true }],
    ],

    axios: {
        proxy: true,
        credentials: true,
    },
    proxy: {
        '/api': {
            target: "http://custom-server.com",
            pathRewrite: {
                '^/api' : "/v1"
            },
            changeOrigin: true,
        },
    },
}

Examining my component:

<script>
export default {
    data() {
        return{
            placesServer:false,
            placesBrowser:false,
        }
    },
    async asyncData ({ $axios }) {
        // Server-side rendering works fine here
        let response = await $axios.get("/api/places");
        return {
            placesServer:response.data,
        };
    },
    created(){
        if (process.browser){
            // Issue occurs here =( when requesting from the browser
            this.$axios.get("/api/places").then((response)=>{
                this.placesBrowser = response.data;
            });
        }else{
            // Works fine here! When not in the browser
            this.$axios.get("/api/places").then((response)=>{
                this.placesBrowser = response.data;
            });
        }
    }
}
</script>

Answer №1

If the API URL you are using is

http://custom-server.com/api/v1/api/places

You will need to make the following changes to the provided code and gain an understanding of the Vue.js/Nuxt.js lifecycle.

export default {
    mode: 'universal',
    buildModules: [],
    modules: [
        '@nuxtjs/axios',
        '@nuxtjs/proxy',
        ['@nuxtjs/dotenv', { systemvars: true }],
    ],

    axios: {
        proxy: true,
    },
    proxy: {
        '/api': {
            target: "http://custom-server.com",
            pathRewrite: {
                '^/api' : ""
            },
        },
    },
}

The code inside the created() hook needs to be changed to another lifecycle method or moved inside a method as per your requirements.

Answer №2

By including the prefix in axios within the nuxt.config.js, I was able to achieve success.

axios: {
 proxy: true,
 credentials: true,
 prefix: '/api/'
}

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

The ASP.NET MVC3 form collection registers as 0 when performing a jQuery ajax post

I'm currently developing a project on ASP.NET MVC3. My current challenge involves POSTing to a method that should return a set of data using the jQuery.ajax api. However, upon handling the request on the server, I noticed that the form collection&apo ...

Is there a way to determine if the X and Z coordinates are colliding with a specific mesh in Three.js without relying on mouse input?

Background Context I'm currently developing a strategy game that combines elements from both Europa Universalis 4 and Age of Empires 3. The game is being created using JavaScript and the Three.js (r109) library. At this stage, I have successfully imp ...

Establish a connection with the hivemq broker using MQTT protocol

Within my app.js file: const mqtt = require('mqtt') const client = mqtt.connect('mqtt://localhost:1883') topic = 'testTopic' client.on('connect', ()=> { client.subscribe(topic) }) client.on(&a ...

A guide to applying ngClass to spans using ngFor according to the value stored in localStorage

When I try to add the active-span class to an element after selecting a size, it's easy to do with jQuery but I'm finding it a bit confusing when trying to achieve the same in Angular. The goal is to have the active-span class added when a size ( ...

Enter the spotlight with all the information you need about AngularJS

Can someone please help me figure out how to display the post->id with a fade in effect? I've tried searching for a solution but haven't had any luck. Your assistance would be greatly appreciated!!! *I apologize in advance if my language is n ...

Manipulate the visibility of a child element's dom-if based on a property retrieved from the parent element

Exploring the world of Polymer, I am eager to tackle the following scenario... I have a binding variable called {{readonly}} that sends data from a parent Dom-HTML to a child Dom-HTML in my Polymer project. The code excerpt looks something like this... C ...

What is the best method for packaging a React component library?

Currently, I am working on developing a React component library that I aim to distribute via npm to reach a wide audience. In my development process, I utilize webpack and babel for packaging and code processing. However, as a newcomer to webpack, I am uns ...

Changing text inside ion-header-bar directive

When utilizing the ion-header-bar directive, I have the left side designated as class="button", the middle section containing <h1> with the word "Recent", and the right side as <ng-icon>. The text on the left side is dynamically generated usin ...

Adjust the positioning of an HTML element in relation to another to prevent elements from moving erratically

Currently, I am working on a website where I have implemented some javascript to achieve a 'typewriter' effect for the prominent middle-centered text displayed below. The script is designed to animate the text by typing it letter by letter in a f ...

Leveraging data within Gatsby to dynamically generate and display content

I am encountering a problem as a newcomer to Gatsby. In my EventsContainer, I have an UpcomingEvent component where I need to render specific data only when upcomingEvent is true. While I successfully utilized map for EventCard, I'm struggling to do t ...

animation of several rows in a table with ng-animate is not feasible

I'm working on highlighting items when they appear in a table. There might be multiple items appearing simultaneously, but it seems like ng-animate is not handling this situation correctly. In the provided example below, you can observe that the div ...

Is it possible to combine the use of 'res.sendFile' and 'res.json' in the same code?

At the moment, my Express app utilizes a controller to manage routing. When a specific route is accessed, I trigger pagesController.showPlayer which sends back my index.html. This is what the controller looks like: 'use strict'; var path = requ ...

Is it possible for jQuery to execute in a sequential manner?

Below is the code I am working with: https://jsfiddle.net/c4zquo60/1/ CSS: #bg { background-repeat: no-repeat; position: absolute; top:0; bottom:0; left:0; right:0; width:100wh; height:100vh; z-index: -1; opacity: ...

Duplicating an array retrieved through a jQuery ajax request

Currently, I am encountering an issue while attempting to duplicate a JSON array within this specific JavaScript function: var test = new array(); function showUser(user, pass, remember) { $.getJSON("login.php", { username : user, password : pass, che ...

Start a Draft.js Editor that includes an unordered list feature

I am trying to pre-populate a draft.js editor with an unordered list made from an array of strings. Here is the code I have so far: const content = ContentState.createFromText(input.join('*'), '*') const editorState = EditorState.crea ...

The Express API will only provide the initial key-value pair of an object in the response

I'm working on fetching nested data objects. Although I can successfully retrieve the object data in the console, I encounter an issue when attempting to access this data using return res.json(imageObject). Instead of retrieving all key-value pairs of ...

dismiss facial recognition event

Does anyone know how to implement a cancel button in Facebox when using it to delete data from MySQL? I want the window to unload when the user clicks on cancel. This is the code snippet I am currently using with Facebox: Are You Sure You Want To Delete ...

Require a split dropdown feature that does not rely on bootstrap

After searching extensively for a split button dropdown field without relying on any bootstrap package, I came up empty-handed. It seems like such a specific feature is hard to find without external dependencies. https://i.sstatic.net/stoMz.png ...

Tips for implementing a switch-case statement with variable formats that may not always be

switch (req.path) { case "/api/posts": console.log("posts"); break; case "/api/posts/tags/*": // the part * is always changing depending on user input console.log("tags"); break; case "/api/best": console.log ...

Is there a way to invoke a jQuery function from an ASP.NET environment?

I'm having trouble figuring out how to properly invoke a jQuery function. ScriptManager.RegisterStartupScript(GetType(), "Javascript", "countdown(); ", true); The issue is that it attempts to call the method inline, preventing it from executing the ...