lifeomic / axios-fetch Goto Github PK
View Code? Open in Web Editor NEWA WebAPI Fetch implementation backed by an Axios client
License: MIT License
A WebAPI Fetch implementation backed by an Axios client
License: MIT License
To see what happens to your code in Node.js 10, Greenkeeper has created a branch with the following changes:
.travis.yml
package.json
files, so that was left aloneIf 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.
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 🤖
There is a collection of frequently asked questions. If those don’t help, you can always ask the humans behind Greenkeeper.
Your Greenkeeper Bot 🌴
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
2.3.0
to 2.4.0
.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.
See CHANGELOG.
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
There is a collection of frequently asked questions. If those don’t help, you can always ask the humans behind Greenkeeper.
Your Greenkeeper Bot 🌴
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
.
2.4.0
to 2.5.0
.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.
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
There is a collection of frequently asked questions. If those don’t help, you can always ask the humans behind Greenkeeper.
Your Greenkeeper Bot 🌴
npmjs is missing
Can you publish those?
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.
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
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.
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?
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.
3.0.2
to 3.0.3
.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.
As suggested by NPM and Snyk.
The new version differs by 1 commits.
aa2519c
dependency security audit fixes from npm & snyk (#210)
See the full diff
There is a collection of frequently asked questions. If those don’t help, you can always ask the humans behind Greenkeeper.
Your Greenkeeper Bot 🌴
2.1.0
to 2.2.0
.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.
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
We're now faking the new hasColors()
method for better compatibility with Node.js 12. d399797
We've removed Node.js 11 from our test matrix. You should upgrade to Node.js 12. 90acbb9
Thank you @langri-sha, @keyspress, @cdaringe and @okyantoro. We couldn't have done this without you!
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.
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
There is a collection of frequently asked questions. If those don’t help, you can always ask the humans behind Greenkeeper.
Your Greenkeeper Bot 🌴
Currently index.ts
is being used as types
in package.json which is causing compiler errors when upgrading to newer versions of typescript (since it tries to compile the entire package instead of just referencing the types). I think this could be resolved by generating an index.d.ts
and referencing that instead.
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
.
The version of node-fetch used for your tests has a vulnerability: https://ossindex.sonatype.org/vulnerability/CVE-2022-0235?component-type=npm&component-name=node-fetch&utm_source=auditjs&utm_medium=integration&utm_content=4.0.37
This issue has been fixed in the 3.x branch of node-fetch.
Could you please update your dependency so that this vulnerability is not carried over in other projects?
Thanks in advance.
11.8.2
to 11.9.0
.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.
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
There is a collection of frequently asked questions. If those don’t help, you can always ask the humans behind Greenkeeper.
Your Greenkeeper Bot 🌴
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?
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.
The Fetch API provides a method for aborting an ongoing request. Is there a way to use this with the underlying axios
engine, which relies on cancellation tokens?
There's currently stale discussion on axios
to support signal
.
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
Per fetch
's spec it should also accept as "input" a Request
object which current implementation does not support.
7.3.2
to 7.4.1
.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.
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
There is a collection of frequently asked questions. If those don’t help, you can always ask the humans behind Greenkeeper.
Your Greenkeeper Bot 🌴
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.
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!
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';
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
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?
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
A declarative, efficient, and flexible JavaScript library for building user interfaces.
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google ❤️ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.