Giter VIP home page Giter VIP logo

axios-fetch's Introduction

Axios-Fetch

npm Build Status Coverage Status Dependabot Badge

This library exposes a Fetch WebAPI implementation backed by an Axios client instance. This allows a bridge between projects that have pre-configured Axios clients already to other libraries that require Fetch implementations.

Global Response object

It is expected that the global Response object will be available. For testing we use the node-fetch library.

import { Response } from 'node-fetch';
// @ts-expect-error node-fetch doesn't exactly match the Response object, but close enough.
global.Response = Response;

Example

One library that wants a Fetch implementation is the Apollo Link HTTP library. If your project has an existing Axios client configured, then this project can help you use that client in your apollo-link-http instance. Here is some sample code:

const { buildAxiosFetch } = require("@lifeomic/axios-fetch");
const { createHttpLink } = require("apollo-link-http");
const link = createHttpLink({
  uri: "/graphql",
  fetch: buildAxiosFetch(yourAxiosInstance)
});

Transforming requests

It is possible to transform requests before they reach your Axios client by providing an optional argument to buildAxiosFetch. For example, if you wanted a fetch implementation that always set the request timeout to 1 second, you could use code like:

const { buildAxiosFetch } = require("@lifeomic/axios-fetch");
const fetch = buildAxiosFetch(yourAxiosInstance, function (config) {
  config.timeout = 1000;
  return config;
});

Support for IE11

To Support IE11 add following dependencies

 npm install --save isomorphic-fetch
 npm install --save es6-promise

After adding these dependencies import in index.jsx file at top (Need to import before React)

import * as es6Promise from 'es6-promise';
import 'isomorphic-fetch';

es6Promise.polyfill(); // below all import end

axios-fetch's People

Contributors

danperkins avatar davidtanner avatar dependabot[bot] avatar dlannoye avatar ecl1ps avatar greenkeeper[bot] avatar hemp avatar hogpilot avatar indigocarmen avatar izumin5210 avatar jagoda avatar joedimarzio avatar loscm avatar mdlavin avatar mlnchk avatar msftenhanceprovenance avatar playdohdoh avatar qnighy avatar swain avatar vikas-kumar56 avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

axios-fetch's Issues

An in-range update of node-fetch is breaking the build 🚨

The dependency node-fetch was updated from 2.3.0 to 2.4.0.

🚨 View failing branch.

This version is covered by your current version range and after updating it in your project the build failed.

node-fetch is a direct dependency of this project, and it is very likely causing it to break. If other packages depend on yours, this update is probably also breaking those in turn.

Status Details
  • continuous-integration/travis-ci/push: The Travis CI build failed (Details).

Release Notes for v2.4.0

See CHANGELOG.

Commits

The new version differs by 13 commits.

  • c9805a2 2.4.0 release (#616)
  • 49d7760 Pass custom timeout to subsequent requests on redirect (#615)
  • cfc8e5b Swap packagephobia badge for flat style (#592)
  • 2a2d438 Adding Brotli Support (#598)
  • 05f5ac1 Node 12 compatibility (#614)
  • 432c9b0 support reading blob with stream (#608)
  • 0ad136d Added new reading method to blob
  • bee2ad8 ignore buffers recalculation
  • e996bda Quick readme update
  • 1c2f07f Headers should not accept empty field name (#562)
  • 7d32932 Unify internal body as buffer (#552)
  • 35a4abe Fix spelling mistake (#551)
  • 2d0fc68 Clone URLSearchParams to avoid mutation (#547)

See the full diff

FAQ and help

There is a collection of frequently asked questions. If those don’t help, you can always ask the humans behind Greenkeeper.


Your Greenkeeper Bot 🌴

An in-range update of coveralls is breaking the build 🚨

The devDependency coveralls was updated from 3.0.2 to 3.0.3.

🚨 View failing branch.

This version is covered by your current version range and after updating it in your project the build failed.

coveralls is a devDependency of this project. It might not break your production code or affect downstream projects, but probably breaks your build or test tools, which may prevent deploying or publishing.

Status Details
  • continuous-integration/travis-ci/push: The Travis CI build could not complete due to an error (Details).
  • coverage/coveralls: First build on greenkeeper/coveralls-3.0.3 at 100.0% (Details).

Release Notes for Dependency security updates

As suggested by NPM and Snyk.

Commits

The new version differs by 1 commits.

  • aa2519c dependency security audit fixes from npm & snyk (#210)

See the full diff

FAQ and help

There is a collection of frequently asked questions. If those don’t help, you can always ask the humans behind Greenkeeper.


Your Greenkeeper Bot 🌴

An in-range update of nock is breaking the build 🚨

The devDependency nock was updated from 11.8.2 to 11.9.0.

🚨 View failing branch.

This version is covered by your current version range and after updating it in your project the build failed.

nock is a devDependency of this project. It might not break your production code or affect downstream projects, but probably breaks your build or test tools, which may prevent deploying or publishing.

Status Details
  • continuous-integration/travis-ci/push: The Travis CI build could not complete due to an error (Details).
  • coverage/coveralls: First build on greenkeeper/nock-11.9.0 at 100.0% (Details).

Release Notes for v11.9.0

11.9.0 (2020-02-13)

Features

  • allow passing a function to enableNetConnect() (#1889) (566461b)
Commits

The new version differs by 11 commits.

  • a275769 test: Update got to the latest version and fill in missing coverage (#1825)
  • 566461b feat: allow passing a function to enableNetConnect() (#1889)
  • 11c0542 Require Node 10+ (#1895)
  • e04d61d Update mkdirp to the latest version 🚀 (#1857)
  • 9379f09 Do not return the nock global from cleanAll() (#1872)
  • 6c504c3 Drop support for String constructor (#1873)
  • 1fae725 refactor(test): use Mocha DSL for allow unmocked (#1894)
  • d0694a7 ci: move semantic-release to GitHub Action
  • 524dd29 test: fix assertRejects usage (#1890)
  • 5d3b270 refactor(test): Chai assert allow unmocked (#1891)
  • 5eaa5f5 Bump lolex and sinon (#1887)

See the full diff

FAQ and help

There is a collection of frequently asked questions. If those don’t help, you can always ask the humans behind Greenkeeper.


Your Greenkeeper Bot 🌴

`.finally()` is not a function

This issue appears to be an upstream issue with node-fetch with it's home grown promises, but this does cause errors with when attempting to use this library with others that do expect .finally() to exist.

It seems that the next version of node-fetch will support promises, so that is worth keeping an eye on.

1.5.0 Release breaks Apollo

With this release no JSON can be parsed. The error in the browser is The provided value 'stream' is not a valid enum value of type XMLHttpRequestResponseType along with being unable to parse JSON

An in-range update of sinon is breaking the build 🚨

The devDependency sinon was updated from 7.3.2 to 7.4.1.

🚨 View failing branch.

This version is covered by your current version range and after updating it in your project the build failed.

sinon is a devDependency of this project. It might not break your production code or affect downstream projects, but probably breaks your build or test tools, which may prevent deploying or publishing.

Status Details
  • continuous-integration/travis-ci/push: The Travis CI build failed (Details).
  • coverage/coveralls: First build on greenkeeper/sinon-7.4.1 at 100.0% (Details).

Commits

The new version differs by 44 commits.

  • 671330c Update docs/changelog.md and set new release id in docs/_config.yml
  • dce58d4 Add release documentation for v7.4.1
  • 56b00a7 7.4.1
  • 7637eef Update CHANGELOG.md and AUTHORS for new release
  • 9b61f26 Update nise and lolex (minor versions)
  • e4f9ad4 Make eslint happy
  • a9fedea npm audit
  • 9a34598 Upgrade mocha to v6
  • 55231d5 Update @babel/core and babel-plugin-istanbul
  • 33f0163 Update @sinonjs/referee and fix deprecations
  • 6caa89b Update @sinonjs/samsam
  • 0bd5066 Update puppeteer and mochify
  • 985a827 Merge pull request #2063 from dustinfarris/pass-through-class
  • 85d3f2a add docs for callThroughWithNew
  • 8e00c22 use slice to convert arguments object into an array

There are 44 commits in total.

See the full diff

FAQ and help

There is a collection of frequently asked questions. If those don’t help, you can always ask the humans behind Greenkeeper.


Your Greenkeeper Bot 🌴

GET requests have data as string "undefined"

I'm running into an issue where a GET request is failing because the axios.request(config) is being called with an invalid data property:

// config object
{
  ...
  "method": "GET",
  "data": "undefined",
  ...
}

This is due to config.data being set here to String(init.body) when init.body === undefined.

I'll submit a PR for review.

Problem creating production build: Failed to minify the code from this file...

I'm getting an error when I try to create a production build with create-react-app. My package.json currently is using

"@lifeomic/axios-fetch": "bouldercare/axios-fetch"

The build (npm run build) fails with the following error.

Creating an optimized production build...

Failed to compile.



Failed to minify the code from this file: 



 	./node_modules/@lifeomic/axios-fetch/src/index.js:6 



Read more here: http://bit.ly/2tRViJ9

Any ideas why the code would fail to minify?

TypeError: Cannot read properties of undefined (reading 'name')

TypeError: Cannot read properties of undefined (reading 'name')

Its caused by isHeaders at typeUtils.js line 12.

I think it should be using optional chain operator.

const isHeaders = (headers) => headers.constructor.name === 'Headers';
=>const isHeaders = (headers) => headers.constructor?.name === 'Headers';

Not working in IE11

Not working in IE11 becuase In library you are using node-fetch module which does not work in ie11 so please include
require('es6-promise').polyfill();
require('isomorphic-fetch');

top of your code.

Cause of issue: inside node-fetch

var getGlobal = function () {
// the only reliable means to get the global object is
// Function('return this')()
// However, this causes CSP violations in Chrome apps.
if (typeof self !== 'undefined') { console.log('self', self.fetch); return self; }
if (typeof window !== 'undefined') { console.log('window'); return window; }
if (typeof global !== 'undefined') { return global; }
throw new Error('unable to locate global object');
}

var global = getGlobal();
console.log('global', global);
module.exports = exports = global.fetch;

exports.default = global.fetch.bind(global); this line throw exception becuase fetch is undefined in ie11

An in-range update of ava is breaking the build 🚨

The devDependency ava was updated from 2.1.0 to 2.2.0.

🚨 View failing branch.

This version is covered by your current version range and after updating it in your project the build failed.

ava is a devDependency of this project. It might not break your production code or affect downstream projects, but probably breaks your build or test tools, which may prevent deploying or publishing.

Status Details
  • continuous-integration/travis-ci/push: The Travis CI build could not complete due to an error (Details).
  • coverage/coveralls: First build on greenkeeper/ava-2.2.0 at 100.0% (Details).

Release Notes for 2.2.0

Enhancements

You can now specify an alternative config file, using the --config CLI argument. This is useful if you want to run unit tests separately from integration tests, since you can have a config file specific to your integration tests which specifies different glob patterns. 2dae2bf

Bug fixes

We're now faking the new hasColors() method for better compatibility with Node.js 12. d399797

Node.js 11

We've removed Node.js 11 from our test matrix. You should upgrade to Node.js 12. 90acbb9

All changes

v2.1.0...v2.2.0

Thanks

Thank you @langri-sha, @keyspress, @cdaringe and @okyantoro. We couldn't have done this without you!

Get involved

We welcome new contributors. AVA is a friendly place to get started in open source. We have a great article on getting started contributing and a comprehensive contributing guide.

Commits

The new version differs by 9 commits.

  • 2451484 2.2.0
  • e528ad2 Bump dependencies
  • 2dae2bf Implement --config flag
  • 58b2350 Disable deprecation warnings in reporter tests
  • d399797 Fake hasColors() in worker processes
  • 90acbb9 Stop testing Node.js 11, remove from engines entry
  • 533ee4b Link to VSCode debugging recipe
  • dc91725 Fix grammar in readme
  • 851316f Remove Flow references

See the full diff

FAQ and help

There is a collection of frequently asked questions. If those don’t help, you can always ask the humans behind Greenkeeper.


Your Greenkeeper Bot 🌴

Unable to integrate with Angular

Hello,

I had initiate a new project with Angular, and install the following packages:

  • angular-apollo
  • apollo-upload-client
  • @lifeomic/axios-fetch
  • axios

to test onUploadProgress but I get the following error:

./node_modules/@lifeomic/axios-fetch/src/typeUtils.ts - Error: Module build failed (from ./node_modules/@ngtools/webpack/src/ivy/index.js):
Error: <PATH\node_modules\@lifeomic\axios-fetch\src\typeUtils.ts is missing from the TypeScript compilation. Please make sure it is in your tsconfig via the 'files' or 'include' property.

I think the problem is the tsconfig.json file.

Best regards

Promise<Response>' is not assignable to type 'AxiosFetch'

After the latest update, the following error occurs when attempting to import the library into a strict TypeScript project.

node_modules/@lifeomic/axios-fetch/src/index.ts:71:3 - error TS2322: Type '(input?: string | undefined, init?: FetchInit | undefined) => Promise<Response>' is not assignable to type 'AxiosFetch'.
  Type 'Promise<Response>' is missing the following properties from type 'Response': clone, headers, ok, redirected, and 14 more.

71   return axiosFetch.bind(undefined, axios, transformer);

This appears to be because the .ts files are being published along side the .js files rather than simple .d.ts declarations.

Recommendation, have tsc output to a dist folder and publish that with a declared types in your package.json.

Another Recommendation, attempt to compile in strict mode and fix the type errors to reduce potential bugs.

Support 204 no-content for node 18

In Node.js 18, an experimental global fetch API is available by default (https://nodejs.dev/en/blog/announcements/v18-release-announce#fetch-experimental). axios-fetch currently assumes node-fetch as the underlying fetch mechanism.

This has compatibility issues in Node v18's fetch implementation for handling of 204 no-content results.

Nodes fetch (backed by undici) expects a 204 response to have a nullable body, however axios-fetch returns an empty buffer, resulting in the following error

TypeError {
    message: 'Response constructor: Invalid response status code 204',
}

The expectation is that axios-fetch also returns a nullable body for 204 no-content responses.

The current workaround to this is to avoid utilising nodes fetch impl via --no-experimental-fetch or override our global references with node-fetch

An in-range update of form-data is breaking the build 🚨

The dependency form-data was updated from 2.4.0 to 2.5.0.

🚨 View failing branch.

This version is covered by your current version range and after updating it in your project the build failed.

form-data is a direct dependency of this project, and it is very likely causing it to break. If other packages depend on yours, this update is probably also breaking those in turn.

Status Details
  • continuous-integration/travis-ci/push: The Travis CI build could not complete due to an error (Details).

Release Notes for Added Types
  • Added TS types
  • Improved documentation
Commits

The new version differs by 18 commits.

  • 905f173 Bumped version to 2.5.0
  • 19add50 Updated dependencies
  • 423c32d Merge pull request #429 from JBtje/master
  • d88f912 - Fixed: filesize is not a valid option? knownLength should be used for streams
  • ddeaa2a Merge branch 'master' of https://github.com/form-data/form-data
  • 37350fa - Fixed: Typos
  • e93ed8d - Fixed: rendering of subheaders
  • ae2b25d Merge pull request #431 from form-data/feat/add-typings
  • 65e78f5 chore: move @types/node to devDep
  • 2721ad7 Merge pull request #430 from alexindigo/master
  • 508b626 Bump notion of modern node to node8
  • e3d8628 Updated deps and readme
  • fc61c73 Switched to Travis Windows from Appveyor
  • 21323f3 - Added: public methods with information and examples to the readme file.
  • 0fb2f57 Merge pull request #428 from form-data/feat/add-typings

There are 18 commits in total.

See the full diff

FAQ and help

There is a collection of frequently asked questions. If those don’t help, you can always ask the humans behind Greenkeeper.


Your Greenkeeper Bot 🌴

Cookies

Cookies without this module are passed to requests, I tried creating an instance of axios with the withCredentials option, the cookies will get passed.

How are cookies passed?

buildAxiosFetch not adding X-XSRF-TOKEN header on requests

Hello,
Thank you for the library, it is very useful.
I encountered a problem I didn't have before, I unfortunately do not remember the last version of axios it worked with.
basically, I am using this library to with my own axios instance and urql to fetch datafrom a graphql server without having to configure urql for csrf.
I updated my dependencies to the latest versions today and tried to make some request but they all fail with an incorrect csrf token error.
Checking the request headers showed that the X-XSRF-TOKEN header is not set for graphql post request, but normal axios request automatically set the header.
I tried setting up an interceptor on the axios instance to log the config, but it also only works when making regular axios request.

Axios

import { boot } from 'quasar/wrappers';
import Axios, { AxiosInstance } from 'axios';

declare module '@vue/runtime-core' {
  interface ComponentCustomProperties {
    $axios: AxiosInstance;
  }
}

const axios = Axios.create();
axios.defaults.withCredentials = true;
axios.interceptors.request.use(
  (config) => {
    console.log('config: ', config);
    return config;
  },
  (error) => {
    return Promise.reject(error);
  }
);

export default boot(async ({ app }) => {
  await axios.get(`${process.env.API_URL}/auth/csrf-token`);
  app.config.globalProperties.$axios = axios;
});

export { axios };

urql

import { createClient as createWSClient } from 'graphql-ws';
import { buildAxiosFetch } from '@lifeomic/axios-fetch';
import axios from 'axios';
import { authExchange } from '@urql/exchange-auth';
import { AuthState } from 'src/interfaces';
import { useJwt } from '@vueuse/integrations/useJwt';

const getAuth = async () => {
  const token = localStorage.getItem('token');
  if (!token) {
    return token ? { token } : null;
  }
  const result = await axios.get<string>(
    `${process.env.API_URL}/auth/refresh-token`
  );
  if (result.data) {
    localStorage.setItem('token', result.data);
    return {
      token: result.data,
    };
  }
  localStorage.clear();
  //logout logic here
  return null;
};

const wsClient = createWSClient({
  url: `${process.env.API_WS_URL}/graphql`,
  connectionParams: async () => ({
    authToken: (await getAuth())?.token,
  }),
});

const client = createClient({
  fetch: buildAxiosFetch(axios),
  url: `${process.env.API_URL}/graphql`,
  requestPolicy: 'cache-and-network',
  exchanges: [
    dedupExchange,
    cacheExchange,
    authExchange({
      addAuthToOperation: ({ authState, operation }) => {
        const state = authState as AuthState;
        if (!state || !state.token) {
          return operation;
        }
        const fetchOptions =
          typeof operation.context.fetchOptions === 'function'
            ? operation.context.fetchOptions()
            : operation.context.fetchOptions || {};
        return makeOperation(operation.kind, operation, {
          ...operation.context,
          fetchOptions: {
            ...fetchOptions,
            headers: {
              ...fetchOptions.headers,
              Authorization: `Bearer ${state.token}`,
            },
          },
        });
      },
      willAuthError: ({ authState }) => {
        const state = authState as AuthState;
        if (!state || !state.token) return true;
        const { payload } = useJwt(state.token);
        if (payload.value && payload.value.exp) {
          const isTokenExpired = payload.value.exp * 1000 < Date.now();
          return isTokenExpired;
        }
        return !!payload;
      },
      didAuthError: ({ error }) => {
        return error.graphQLErrors.some(
          (err) => err.extensions?.code === 'FORBIDDEN'
        );
      },
      getAuth,
    }),
    multipartFetchExchange,
    subscriptionExchange({
      forwardSubscription(operation) {
        return {
          subscribe: (sink) => {
            const dispose = wsClient.subscribe(operation, sink);
            return {
              unsubscribe: dispose,
            };
          },
        };
      },
    }),
  ],
});

export default boot(({ app }) => {
  app.use(UrqlPlugin, client);
});

axios: v0.26
@lifeomic/axios-fetch: v3.0.0
@urql/vue: v0.6.1

Form-data not serializing correctly

I'm using this package as a fetch implementation for the Apollo Client in Gatsby. I want to upload files to the server, so I'm using the package: apollo-upload-client. But when inspecting the payload that gets sent, it says:

[object FormData], instead of serializing everything.

Any suggestions on how to fix this?

Unable to import useAxiosFetch as an ES6 module

Hello guys, hope you are well!
First of, thanks for developing this awesome library, much appreciated! ❤️

I'm trying to import useAxiosFetch in my React app as an ES6 module:
import { useAxiosFetch } from '@lifeomic/axios-fetch'

Unfortunately, I'm getting the following error:

fromRequireContextWithGlobalFallback.js:21 ReferenceError: exports is not defined
    at Module../node_modules/@lifeomic/axios-fetch/src/index.js (index.js:15)

Lines causing error:

Object.defineProperty(exports, "__esModule", {
  value: true
});

Could you please let me know what could be the cause of it?

I'm using v2.0 with Webpack. Let me know if you need me to provide any additional details.

Version 10 of node.js has been released

Version 10 of Node.js (code name Dubnium) has been released! 🎊

To see what happens to your code in Node.js 10, Greenkeeper has created a branch with the following changes:

  • Added the new Node.js version to your .travis.yml
  • The new Node.js version is in-range for the engines in 1 of your package.json files, so that was left alone

If you’re interested in upgrading this repo to Node.js 10, you can open a PR with these changes. Please note that this issue is just intended as a friendly reminder and the PR as a possible starting point for getting your code running on Node.js 10.

More information on this issue

Greenkeeper has checked the engines key in any package.json file, the .nvmrc file, and the .travis.yml file, if present.

  • engines was only updated if it defined a single version, not a range.
  • .nvmrc was updated to Node.js 10
  • .travis.yml was only changed if there was a root-level node_js that didn’t already include Node.js 10, such as node or lts/*. In this case, the new version was appended to the list. We didn’t touch job or matrix configurations because these tend to be quite specific and complex, and it’s difficult to infer what the intentions were.

For many simpler .travis.yml configurations, this PR should suffice as-is, but depending on what you’re doing it may require additional work or may not be applicable at all. We’re also aware that you may have good reasons to not update to Node.js 10, which is why this was sent as an issue and not a pull request. Feel free to delete it without comment, I’m a humble robot and won’t feel rejected 🤖


FAQ and help

There is a collection of frequently asked questions. If those don’t help, you can always ask the humans behind Greenkeeper.


Your Greenkeeper Bot 🌴

Do not require `node-fetch` for browser targets

Currently, the library solely depends on node-fetch for providing fetch primitives like Header class and so on.

We plan to use it in the browser context, where these primitives are provided by the runtime and we would like to avoid packing node-fetch because of it. I would like to provide a similar abstraction that https://github.com/sindresorhus/ky-universal uses for NodeJS and browser, utilizing the browser property in package.json.

Error raised if someone goes offline and attempts a request

Hi! I'm running into an issue where, if someone attempts a request while they are offline, result.headers on line 40 blows up because err.response is undefined. I'm unsure of the proper way to go about fixing this, or if there is something I should be doing with the axios instance before passing it to axios-fetch to avoid this issue altogether.

Any help would be greatly appreciated!

Error fetching and displaying characters from other languages

Hello,

I am using axios fetch with @urql/vue to fetch data but it causes characters (french, japanese) to be incorrectly displayed.
The following is the code I use.

import { boot } from 'quasar/wrappers';
import urql, {
  createClient as createUrqlClient,
  dedupExchange,
  makeOperation,
  Exchange,
} from '@urql/vue';
import { cacheExchange } from '@urql/exchange-graphcache';

import { multipartFetchExchange } from '@urql/exchange-multipart-fetch';
import { buildAxiosFetch } from '@lifeomic/axios-fetch';
import Axios from 'axios';

import { devtoolsExchange } from '@urql/devtools';

export default boot(async ({ app }) => {
  const axios = Axios.create({
    baseURL: `${process.env.API_URL}`,
  });
  axios.defaults.withCredentials = true;

  const exchanges: Exchange[] = [
    devtoolsExchange,
    dedupExchange,
    cacheExchange({}),

    multipartFetchExchange,
  ];

  const client = createUrqlClient({
    fetch: buildAxiosFetch(axios) as unknown as typeof fetch,
    url: `${process.env.API_URL}/graphql`,
    requestPolicy: 'cache-and-network',
    exchanges,
  });
  app.use(urql, client);
});

I tried with axios only and also urql without axios-fetch and they both display characters correctly.

axios-fetch won't let me intercept 401 failed requests

I can't use axios-fetch with together with https://github.com/Flyrell/axios-auth-refresh, because the errors seem to get thrown in a way that cannot be intercepted.

For example,

const refreshAuthLogic = (failedRequest: any): Promise<any> => {
...
}

createAuthRefreshInterceptor(axios, refreshAuthLogic, { skipWhileRefreshing: false });

const httpLink = createHttpLink({
  uri: '/backend/graphql/',
  fetch: buildAxiosFetch(axios),
});

This works for requests done through axios, but not for apollo requests. The errors that get thrown can't get intercepted by refreshAuthLogic.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.