There are no headers present in the response from apollo-client

I am currently utilizing a graphql api along with a vue.js frontend that incorporates the apollo client for fetching data from the backend. This setup has been operating smoothly thus far.

In each response header, the server sends back a new JWT-Token which is essential for my application. In order to handle this, I planned on implementing an afterware using the afterware, which would extract the new token from every response and update the corresponding storage entry. However, there seems to be an issue as the headers are showing up empty.

Below is the current implementation of the afterware:

apolloClient.networkInterface.useAfter([{
    applyAfterware({ response }, next) {
        if (process.env.NODE_ENV === 'development') {
            console.log('got new response', response);
        }
        if (response.status === 401) {
            store.commit('logout');
            store.commit('routeLogin');
        }
        next();
    }
}]);

This is how the response appears:

https://i.sstatic.net/uI9io.png

And this is what was actually sent:

https://i.sstatic.net/nCCRs.png

Am I overlooking something in my implementation?

UPDATE

I came across a similar issue in the project's issue tracker, which had a resolution involving adding Access-Control-Expose-Headers. In response, I added them to my server configuration. Despite these changes, the response still fails to populate apollo's headers object as expected:

https://i.sstatic.net/ZdhEZ.png

Answer №1

You should eliminate {}.

from:

applyAfterware({res}, next) {

to:

applyAfterware(res, next) {

and now you will receive the complete header information.

apolloClient.networkInterface.useAfter([{
applyAfterware(res, next) {
        console.log("response:", res.options.headers);
        if (res.response.status === 401) {
            store.commit('logout');
            store.commit('routeLogin');
            // logout();
        }
        next();
    }
}]);

Answer №2

If you're searching for a method to access the response headers, I have a finalized solution that might help:

import _ from 'lodash';
import Vue from 'vue';
import VueApollo from 'vue-apollo';
import { ApolloClient } from 'apollo-client';
import { HttpLink } from 'apollo-link-http';
import { ApolloLink, from } from 'apollo-link';
import { onError } from 'apollo-link-error';
import { InMemoryCache } from 'apollo-cache-inmemory';

...

const apolloProvider = new VueApollo({
    clients: {
        default: defaultClient,
        admin: adminClient
    },
    defaultClient
});

Vue.use(VueApollo);

export default apolloProvider;

Please note that in order to retrieve the specific headers on the server side, you need to ensure they are exposed correctly.

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 expandable row remains open even after filtering the table with JavaScript

An expandable row in the table displays details of rows. I have implemented a JavaScript search and filter function to find specific row content. However, when using the search filter, it successfully shows results but does not expand the details as intend ...

Difficulty arises when attempting to run code when a checkbox is not selected

In my form validation process, I am facing an issue where I need to validate certain values only if a checkbox is unchecked. If the checkbox is checked, I want to use the values that were previously added. However, none of the existing code snippets seem t ...

Utilize Next.js and GSAP to dynamically showcase images upon hovering over the title

I have a dynamic list of titles that I want to enhance by displaying images when hovering over each title. The issue I'm facing is that when I hover over one title, all the images display at once. As a React beginner, I believe the solution should be ...

Vue components fail to display properly when transitioning between routes in Vue (version 3) using the Vue Router

Just diving into VueJS version 3 and vue-router. Despite my efforts to troubleshoot by consulting Stack Overflow and Google, the issue remains unresolved. I have defined two routes: /login /admin/index The Problem: While the login route ...

Having trouble viewing the image slider on an HTML webpage

I've been attempting to incorporate an image slider into my personal website on GitHub, but I've encountered some difficulties as the images are not displaying. Interestingly, I can load individual images without using the slider and they show up ...

Issue with setState not being triggered within axios POST request error handling block

I am in the process of setting up an error handler for a React Component called SignupForm.js, which is responsible for handling user registrations. Specifically, I am working on implementing a handler to deal with cases where a user tries to sign up with ...

What could explain why the event listener functions properly on the initial call but fails on subsequent calls?

Currently, I am working on a bootstrap carousel where the "Previous" button is hidden on the first slide and the "Next" button is hidden on the last slide. Now, I want to disable the next button on the second slide (and eventually all slides with iframe vi ...

Forwarding based on URL/Query Parameters

I'm looking to create a redirect for users based on URL or query parameters, but I'm not sure how to go about it. For example, if the URL is https://www.tamoghnak.tk/redirect?link=https://www.tamoghnak.tk/gobob, I want to redirect to /gobob. If ...

"Customizing the Material-ui TextField DOM Element: A Step-by-Step

After trying the code below, I was expecting to see a yellowish "Hi," but instead received [object Object]. Is there a way to correct this issue? Possibly utilizing InputProps would help, but I haven't been able to locate a comprehensive tutorial on ...

Displaying a progress bar while fetching data in Vue: A step-by-step guide

I am working on developing a progress bar using vue js and bootstrap for my desktop application. Within the template, I have the code that will generate the necessary markup: <div class="container-fluid p-0 vh-100" v-if="isLoading&quo ...

I encountered an issue where I am unable to subtract from jQuery's .outerHeight() within an if statement

I've been working on creating an ajax request that triggers when a div is scrolled to the bottom. I thought I had it figured out with this code, but I've run into an issue. Everything works fine without subtracting 100 from the elem.outerHeight() ...

Tips for activating text selection in PDF.js

Struggling to enable text selection in PDF.js after successfully displaying a PDF? Seeking a simple example to guide you through the process? Despite trying various approaches, I haven't achieved the desired outcome yet. My current code snippet is a ...

Vuetify's v-text-field not properly aligning text to the center

The alignment of the text in v-text-field is causing issues for me, as I am unable to center it. Despite attempting various solutions, I have not been successful. 1. <v-text-field type="number" class="mr-2 text-center"></v-te ...

Place a checkbox at the start of each table cell

Is there a way to add a checkbox before the text in the first cell of each row in an HTML table using jQuery? I attempted this method: $("table td:first-child").each(function() { $(this).prepend('<input type="checkbox" class="basic-kpi-row"/&g ...

Incorporate a new CSS class into a DIV using JavaScript

Sample HTML: <div id="bar" class="style_one"></div> Is there a way to include the class style_two without deleting style_one? final outcome: <div id="bar" class="style_one style_two"></div> ...

Where should the logic for the Redux app be implemented for optimal performance?

My react-redux app features an action-creator that filters a list of objects based on a specified title: export const filterItems = (title) => dispatch => { axios.get(`/api/items/?title=${title}`) .then(res => { dispatch({ ...

Setting up and customizing Express with Angular

Currently working on a straightforward Angular/Express todo-list app, I encountered some difficulties. As the project is still in progress, after running the code on localhost:3000, I noticed that {{ thing }} was displayed literally on the webpage. The di ...

Issue with JavaScript ScrollTop

Simply put, I am trying to determine the total scroll size for a text area in a unit that scrollTop can align with. However, I am at a loss on how to do so. I've tried scrollHeight and various other methods without success. Any advice or suggestions ...

The onFocus event ceases to trigger once the modal popup appears

One issue that I am facing is with an onfocus event handler. Initially, everything works perfectly after the page loads. However, when I click on a link that triggers a modal popup, the onfocus event stops working. Although focus continues to work as expec ...

AngularJS date formatting fails to properly format dates

{{ map.thedate }} The result is 2014-06-29 16:43:48 Even after using the following code, it still displays the same date as above. {{ map.thedate | date:'medium' }} ...