nestjs / axios Goto Github PK
View Code? Open in Web Editor NEWAxios module for Nest framework (node.js) 🗂
Home Page: https://docs.nestjs.com/techniques/http-module
License: MIT License
Axios module for Nest framework (node.js) 🗂
Home Page: https://docs.nestjs.com/techniques/http-module
License: MIT License
It is not really a big issue but, as you give already deprecation warnings for the old version
DEPRECATED! "HttpModule" (from the "@nestjs/common" package) is deprecated and will be removed in the next major release. Please, use the "@nestjs/axios" package instead.
I think it would be best to align version numbers to the other nestjs packages
bump the version to 8.x.x
No response
.
No response
0.0.1 -> 0.0.5
[email protected] is recommended version only.
Another package (@keycloak/[email protected]) uses axios@^0.24.0 as minimum minor required version.
In result i've had @nestjs/[email protected] and [email protected] installed. But it raises TypeScript compilation error:
Type 'Promise<import(".../node_modules/@nestjs/axios/node_modules/axios/index").AxiosResponse<any, any>>' is not assignable to type 'Promise<import(".../node_modules/axios/index").AxiosResponse<any, any>>'
(bla-bla-bla)
get(url: string): Promise<AxiosResponse> {
return lastValueFrom(
this.httpService.get(url)
);
}
Minimum [email protected] installes by default with npm install
command
No response
Axios package version 1.0 and 1.1 has a bug that was resolved in latest version of axios.
Using a retry incerceptor causes axios to fail. See softonic/axios-retry#212
Can you update @nestjs/axios to the latest version of axios?
N/A
Use a retry interceptor like axios-retry with the current version shipped with @nestjs/axios
See softonic/axios-retry#212
See the pull request that fixed the issue: axios/axios#5224
Latest version of axios included in @nestjs/axios that does not suffer from the bug mentioned in softonic/axios-retry#212
1.0.0
9.2.0
16.18.1
No response
Axios frequently updates its types, which can make upgrades difficult. Even the types between patch versions can be incompatible (the AxiosRequestConfig
interfaces are not compatible between versions 1.2.1 and 1.2.2, for example). If you have another library that depends on axios, you can easily end up with a version in the root of node_modules that is incompatible with @nestjs/axios. Given how many of the axios types are exposed by @nestjs/axios, this can lead to confusing error messages.
The best way to mitigate this issue is to explicitly install axios in your project, but that doesn't completely solve the issue because you have to ensure that the version that you install is compatible with the one in @nestjs/axios.
There are two solutions that I can think of:
AxiosResponse
, AxiosRequestConfig
, etc.) and you can't use this package without using the axios types (unless your Typescript config is relatively loose), this seems fair to me. It will also ensure that the axios version in the root is the correct one. I don't believe that there are any drawbacks to this because you can't install an incompatible version of axios right now anyway unless you ignore the type incompatibilities. Since npm also installs peer dependencies automatically now, consumers of this package wouldn't need to explicitly specify an axios version in their package.json file.For option 1, no changes would be required for use - imports would come from axios
as they do today. For a few cases, users might be confused on installation when they have a version of axios that is not compatible. However, I think that npm explicitly informing users of an incompatible peer dependency is a better solution than the cryptic type errors that you receive at the moment (e.g. "AxiosRequestConfig is not compatible with AxiosRequestConfig").
For option 2, users would need to change all imports of axios types to come from this package. For example, import { AxiosResponse } from 'axios'
would become something like import { AxiosResponse } from '@nestjs/axios'
. A note should also be added to the documentation if this is the chosen option.
The current behavior is confusing and occasionally frustrating and the TypeScript error messages aren't very helpful. This would reduce friction when upgrading packages and would prevent confusing error messages.
Update
npm install @nestjs/axios
npm install @nestjs/axios
//TS2305: Module '"@nestjs/axios"' has no exported member 'HttpModule'.
import { HttpModule } from '@nestjs/axios';
To work like 0.0.6
0.0.7
8.0.0
14.17.6
No response
[ ] Regression
[x] Bug report
[ ] Feature request
[ ] Documentation issue or request
[ ] Support request => Please do not submit support request here, instead post your question on Stack Overflow.
This package locks on "axios": "0.21.1"
, while there are open CVEs for below 0.21.4.
Either using latest, using axios as a peer dependency or upgrading to the latest non-vuln version.
https://snyk.io/vuln/SNYK-JS-AXIOS-1579269
Nest version: X.Y.Z
this issue occurs with the latest version of this package at 0.0.1
For Tooling issues:
- Node version: XX
- Platform:
Others:
Upgrading from an older nest 7 to nest 8 system, I saw HttpModule was deprecated and followed the update instructions. But this package is below 1.0 and is using a locked dep too.
The result of this is that a single request is logged as many dependencies on HttpClient I have.
How can I avoid this duplication?
https://gist.github.com/matiasgarcia/53d2aa20acecec511b285efd86525279
No response
Single interceptor added
0.1.0
9.0.11
v16.17.0
No response
I'm trying to use axios as explained in axios documentation but instead I'm getting Observable
s instead of plain old promises from HttpService
.
I would like to have the choice whether I want to use promise or observable based API for axios.
No response
I don't think I should be forced to use axios with only observables, because that is not how axios was built and not how it operates. Maybe there should be separate packages for axios with observables and with promises?
Not sure if you're aware but there is a package axios-observable
that does a similar thing with its createObservable
vs your implementation of makeObservable
.
By adding HttpModule in imports array gives issue of dependency for httpservice in v 0.0.5 by downgrading to v 0.0.4
the issue was resolved.
"dependencies": {
"@nestjs/axios": "^0.0.5",
"@nestjs/common": "^8.0.0",
"@nestjs/config": "^1.1.6",
"@nestjs/core": "^8.0.0",
"@nestjs/passport": "^8.1.0",
"@nestjs/platform-express": "^8.0.0",
"@nestjs/typeorm": "^8.0.3",
}
ERROR [ExceptionHandler] Nest can't resolve dependencies of the HttpService (?). Please make sure that the argument AXIOS_INSTANCE_TOKEN at index [
0] is available in the AuthModule context.
Potential solutions:
https://github.com/nestjs/axios
No response
Adding httpservice normally as it was happening in v0.0.4
0.0.5
8.2.0
14.17.0
No response
Axios allows to define "common" headers. It is not possible to register common headers through the HttpModule.register
method.
For instance :
When invoking the httpService, it is possible to add a value to the common
headers such as :
this.httpService.axiosRef.defaults.headers.common['Authorization'] = axiosResponse.headers.authorization ?? '';
But it is not possible to register the same kind of headers through the HttpModule.register
method :
HttpModule.register({
headers: {
common: { 'Content-Type': 'application/json', Accept: 'application/json' }, // => TS Error
// 'Content-Type': 'application/json',
// Accept: 'application/json',
},
}),
By removing the comments it works though, Axios seems to pick them up. But it seems to be less granular.
Updating the AxiosRequestConfig such as
export interface AxiosRequestConfig<D = any> {
//Removed code
headers?: AxiosRequestHeaders | Partial<HeadersDefaults>;
}
It would allow the flexibility to set up the headers how we see fit while keeping the the actual way of doing things.
No response
A more granular declaration of the headers through the register method that follow the AxiosDefaults deinition
The latest release of nestjs/axios depends on axios 0.25.0. The latest Axios version is 0.26.0.
Publish a new version, since the master branch already depends on 0.26.0.
No response
I want to use the latest version of Axios.
I want to configure two or more HttpServices for use inside my module
So i made a bunch of submodules that does all inside my main module
api.auth.module.ts
import { HttpModule, HttpService } from '@nestjs/axios';
import { Module } from '@nestjs/common';
import { ConfigService } from '@nestjs/config';
export abstract class AuthHttpService extends HttpService {}
@Module({
imports: [
HttpModule.registerAsync({
useFactory: (configSvc: ConfigService) => ({
timeout: 10000,
baseURL: configSvc.get<string>('auth.endpoints.auth')!,
}),
inject: [ConfigService],
}),
],
providers: [{ provide: AuthHttpService, useExisting: HttpService }],
exports: [AuthHttpService],
})
export class AuthAPIModule {}
api.checkout.module.ts
import { HttpModule, HttpService } from '@nestjs/axios';
import { Module } from '@nestjs/common';
import { ConfigService } from '@nestjs/config';
export abstract class CheckoutHttpService extends HttpService {}
@Module({
imports: [
HttpModule.registerAsync({
useFactory: (configSvc: ConfigService) => ({
timeout: 10000,
baseURL: configSvc.get<string>('checkout.endpoints.auth')!,
}),
inject: [ConfigService],
}),
],
providers: [{ provide: CheckoutHttpService, useExisting: HttpService }],
exports: [CheckoutHttpService],
})
export class CheckoutAPIModule {}
api.module.ts
import { Module } from '@nestjs/common';
import { AuthAPIModule } from './modules/api.auth.module';
import { CheckoutAPIModule } from './modules/api.checkout.module';
import { ApiService } from './providers/api.service.provider';
@Module({
imports: [AuthAPIModule, CheckoutAPIModule],
providers: [ApiService ],
exports: [ApiService ],
})
export class ApiModule {}
But when i do something like this on exporting the main module:
console.log('checkout', checkoutHttpService.axiosRef.defaults.baseURL);
console.log('auth', authHttpService.axiosRef.defaults.baseURL);
Both returns undefined.
If i configure everything with HttpModule.register
instead of HttpModule.registerAsync
, somehow it magically works. How can i make this work with registerAsync ?
https://gist.github.com/Allakazan/82619c8183ebdcb799db0e8493ffb1fb
No response
I should be able to use registerAsync with dynamic modules that uses useExisting
3.0.2
8.0.0
20.10.0
No response
Latest published version of https://github.com/nestjs/axios still relies on axios 0.23.0.
Publish a new version, since the master branch already supports 0.24.0.
No response
Be able to update nestjs and axios.
When run nest build
with "@nestjs/axios": "^2.0.0" in package.json, I get this Typescript error:
backend2>nest build
node_modules/@nestjs/axios/dist/http.service.d.ts:14:105 - error TS2707: Generic type 'AxiosResponse<T>' requires between 0 and 1 type arguments.
14 protected makeObservable<T>(axios: (...args: any[]) => AxiosPromise<T>, ...args: any[]): Observable<AxiosResponse<T, any>>;
~~~~~~~~~~~~~~~~~~~~~
Found 1 error(s).
If I'll manually change type in node_modules/@nestjs/axios/dist/http.service.d.ts
from
protected makeObservable<T>(axios: (...args: any[]) => AxiosPromise<T>, ...args: any[]): Observable<AxiosResponse<T, any>>;
to
protected makeObservable<T>(axios: (...args: any[]) => AxiosPromise<T>, ...args: any[]): Observable<AxiosResponse<T>>;
nest build will run without errors.
Looks like a bug, because we expect to receive Observable with type.
https://github.com/vladimirverh/repro-nestjs-2.0.0-TS-issue/blob/main/package.json
yarn install v1.22.10
[1/5] Validating package.json...
[2/5] Resolving packages...
success Already up-to-date.
nest build
node_modules/@nestjs/axios/dist/http.service.d.ts:14:105 - error TS2707: Generic type 'AxiosResponse<T>' requires between 0 and 1 type arguments.
14 protected makeObservable<T>(axios: (...args: any[]) => AxiosPromise<T>, ...args: any[]): Observable<AxiosResponse<T, any>>;
~~~~~~~~~~~~~~~~~~~~~
Found 1 error(s).
nest build should run without Typescript errors.
9.3.6
9.3.6
16.13.1
package.json (in case GitHub url not working):
{
"name": "backend",
"version": "1.0.0",
"engines": {
"node": ">=16.0.0",
"npm": ">=7.0.0"
},
"scripts": {
"prebuild": "rimraf dist",
"build": "nest build",
"start": "nest start",
"start:dev": "nest start --watch",
"test": "mocha --timeout 90000 --exit"
},
"dependencies": {
"@nestjs/axios": "^2.0.0",
"@nestjs/common": "^9.3.6",
"@nestjs/config": "^2.3.0",
"@nestjs/core": "^9.3.6",
"@nestjs/platform-express": "^9.3.6",
"@nestjs/schedule": "^2.2.0",
"@nestjs/typeorm": "^9.0.1",
"bcrypt": "^5.0.1",
"cache-manager": "^3.4.4",
"cache-manager-redis-store": "^2.0.0",
"class-transformer": "^0.5.1",
"class-validator": "^0.14.0",
"cookie-parser": "^1.4.5",
"lodash": "^4.17.21",
"pg": "^8.9.0",
"reflect-metadata": "^0.1.13",
"rimraf": "^3.0.2",
"rxjs": "^7.8.0",
"typeorm": "^0.3.11",
"winston": "^3.7.2",
"yarn": "^1.22.10"
},
"devDependencies": {
"@nestjs/cli": "^9.2.0",
"@nestjs/schematics": "^9.0.4",
"@nestjs/testing": "^9.3.2",
"@types/bcrypt": "^5.0.0",
"@types/cache-manager": "^3.4.2",
"@types/chai": "^4.2.21",
"@types/chai-as-promised": "^7.1.4",
"@types/cron": "^1.7.3",
"@types/express": "^4.17.17",
"@types/body-parser": "^1.19.2",
"@types/faker": "^5.5.8",
"@types/lodash": "^4.14.171",
"@types/mocha": "^9.0.0",
"@types/multer": "^1.4.7",
"@types/newrelic": "^7.0.3",
"@types/node": "^16.18.12",
"@types/sinon": "^10.0.2",
"@typescript-eslint/eslint-plugin": "^4.19.0",
"@typescript-eslint/parser": "^4.19.0",
"chai": "^4.3.4",
"chai-as-promised": "^7.1.1",
"eslint": "^7.22.0",
"eslint-config-prettier": "^8.1.0",
"eslint-plugin-prettier": "^3.3.1",
"faker": "^5.5.3",
"mocha": "^9.0.3",
"nodemon": "^2.0.20",
"prettier": "^2.2.1",
"sinon": "^11.1.2",
"ts-loader": "^8.0.18",
"ts-node": "^9.1.1",
"tsconfig-paths": "^3.9.0",
"typeorm-fixtures-cli": "^1.9.1",
"typescript": "^4.9.5"
}
}
Right now axios.isAxiosError
will return the following error:
TypeError: Cannot read properties of undefined (reading 'isAxiosError')
There is a ticket around this in the axios repository here:
The problem is fixed by updating axios to 1.2.x
Currently if I update and include axios by hand then I get version missmatching on my typing as explained here:
Argument of type 'import("./node_modules/axios/index").AxiosRequestConfig<any>' is not assignable to parameter of type 'import("./node_modules/@nestjs/axios/node_modules/axios/index").AxiosRequestConfig<any>'.
No response
I should be able to call axios.isAxiosError
without it saying that axios is undefined.
This is a known bug for axios v1.1.3, and thus axios should be updated to 1.2.x
1.0.0
9.2.1
16.15.1
No response
Hello! Is there any plan of supporting axios 1.x soon? People are discussing here that updating axios from 0.27.2 to latest 1.x is breaking: axios/axios#5100
Migrate to axios 1.x
No response
NestJS projects will be stuck on 0.x as long as 1.x is not properly supported here
axios package is outdated.
update axios to the latest release (v1.1.3
by now)
https://github.com/axios/axios/blob/v1.x/MIGRATION_GUIDE.md
There's no migration guide, IG, perhaps because axios has no breaking changes.
We should keep up with updates, especially with HTTP clients, IMO.
Since the axios instance is inside the module there is no easy way to add axios interceptors on the instance. Many workarounds suggested rely on the use of onModuleInit of the module which imports the HttpModule, but this aprouch breaks when the service is used on a injectable with scope REQUEST, because onModuleInit only add the interceptor on the first instance generated and not the others instances generated by scope Request.
Expand HttpModuleOptions to add interceptors on the config of the module and add it to the axios instance generated by the module.
No response
Allowing the configuration of interceptors on the axios instance of the http module, i can generate interceptors to add authorization headers, add logging, add metrics, etc. This reduces the amount of times that i had to make wrappers around the module and the service in other to achieve desired behaviors which comes with axios.
The issue appears when the axios 1.2.3+ is explicitly installed in the project. Then, code like this isn't working:
import { HttpService } from '@nestjs/axios';
import { Injectable } from '@nestjs/common';
import { AxiosInstance } from 'axios';
@Injectable()
export class MyService {
private http: AxiosInstance;
constructor(private readonly httpService: HttpService) {
this.http = httpService.axiosRef;
}
}
The reason is that typings and structure for AxiosInstance starting from 1.2.3 and higher is different from what goes with @nestjs/axios
right now.
The internal dependency for Axios is 1.3.0
No response
Typically you grab instances from Axios directly - not from sub-dependences of install packages (@nestjs/axios
in this case).
Axios currently has new Multipart Bodies methods. Would be nice if the HttpService was able to access these.
Add the following functions from the axios library.
No response
Keeping up to date with the capabilities of the Axios library while still allowing for Observables.
Axios has been updated to v0.25.0. Among other things, it includes a fix for a vulnerable dependency (follow-redirects).
Can we get an update to @nestjs/axios with the latest version of Axios? Thanks!
I would like parameters applied to all requests. When I setup my HttpModule
I want to register with parameters
HttpModule.registerAsync({
useFactory: () => ({
params: {
version: '1.3.5',
},
}),
}),
I would like this parameters to be applied on every request. However, there are other parameters I need to apply specific to a request. For those requests I specify a new parameters object and the ones from the registration get overwritten.
this.httpService.get(`/url`,
{
baseURL: this.appConfigService.host,
params:
ids: ids.join(','),
},
To get around this I can do spread the default parameters, but that feels like the equivalent of just adding the parameters manually to every request.
this.httpService.get(`/url`,
{
baseURL: this.appConfigService.host,
params:
...this.httpService.axiosRef.defaults.params,
ids: ids.join(','),
},
I would like HttpService to either merge the params object specified during module registration, or have some sort of config option to indicate that params need to be merged.
No response
Have the ability to have parameters in one place that will apply to all requests in a particular service. This makes it easy so that if a parameter needs to be added for all requests, it can be done in one place instead of updating each request in a service.
Turns this:
this.httpService.get(`/url`,
{
baseURL: this.appConfigService.host,
params:
ids: ids.join(','),
version: "1.2.3"
},
this.httpService.get(`/url/123`,
{
baseURL: this.appConfigService.host,
params:
ids: ids.join(','),
otherParam: 2,
},
into:
this.httpService.get(`/url`,
{
baseURL: this.appConfigService.host,
params:
ids: ids.join(','),
},
this.httpService.get(`/url/123`,
{
baseURL: this.appConfigService.host,
params:
ids: ids.join(','),
otherParam: 2,
},
Currently all methods of the HttpService take a <T = any>
generic parameter, but type data?; any
. It would be nice to enforce types on the data object that gets passed to either AxiosRequestConfig
or the data
parameter, respectively. This also allow it to be compliant with the types that Axios themselves have in their library.
Retype the HttpService as follows:
import { AxiosInstance, AxiosPromise, AxiosRequestConfig, AxiosResponse } from "axios";
import { Observable } from "rxjs";
export declare class HttpService {
protected readonly instance: AxiosInstance;
constructor(instance?: AxiosInstance);
request<T = any, D = any>(config: AxiosRequestConfig<D>): Observable<AxiosResponse<T>>;
get<T = any, D = any>(url: string, config?: AxiosRequestConfig<D>): Observable<AxiosResponse<T>>;
delete<T = any, D = any>(url: string, config?: AxiosRequestConfig<D>): Observable<AxiosResponse<T>>;
head<T = any, D = any>(url: string, config?: AxiosRequestConfig<D>): Observable<AxiosResponse<T>>;
post<T = any>(url: string, data?: any, config?: AxiosRequestConfig): Observable<AxiosResponse<T>>;
post<T extends any, D extends any>(url: string, data: D, config?: AxiosRequestConfig<D>): Observable<AxiosResponse<T>>;
put<T = any>(url: string, data?: any, config?: AxiosRequestConfig): Observable<AxiosResponse<T>>;
put<T extends any, D extends any>(url: string, data: D, config?: AxiosRequestConfig<D>): Observable<AxiosResponse<T>>;
patch<T = any>(url: string, data?: any, config?: AxiosRequestConfig): Observable<AxiosResponse<T>>;
patch<T extends any, D extends any>(url: string, data: D, config?: AxiosRequestConfig<D>): Observable<AxiosResponse<T>>;
get axiosRef(): AxiosInstance;
protected makeObservable<T>(axios: (...args: any[]) => AxiosPromise<T>, ...args: any[]): Observable<AxiosResponse<T, any>>;
}
This way with overloading, if we provide the type then data
becomes required.
No response
Just allowing the option to enforce stricter typing.
I will be easier to expose AxiosError type (like for AxiosResponse #100), it will avoid installing axios package
Add AxiosError in
import Axios, {
AxiosInstance,
AxiosPromise,
AxiosRequestConfig,
AxiosResponse,
CancelTokenSource,
} from 'axios';
in this httpservice file https://github.com/nestjs/axios/blob/master/lib/http.service.ts
And export it, or in interfaces/HttpModule.interface
After this part AxiosResponse is an interface exported from the axios package ($ npm i axios).
in https://docs.nestjs.com/techniques/http-module whe cousl add this : We also expose AxiosError to ease error type handling
We may also remove the fact that we need to install axios package as it's a dependency, and already installed
We handle error on dependency service calls, and depending on response we handle it with a try / cacth and with TS 4.4 changes, we would like to do something like
catch(error: unknown) {
if (error instanceOf AxiosError) {
switch (error?.response?.status) {
case 404:
return []
case 400:
throw new CompanyIdInvalid('Company not found', path);
}
}
}
Like explained in axios/axios#5346 and also in #641 there is a problem with v1.2.1 of the axios package. Unfortunately there hasn't been a version bump that's usable for projects that still use Nest v8.
We can't currently upgrade to Nest v9, so it would be fantastic, if there was a bump in the dependency version.
No response
Should be able to use the httpService without the above mentioned bug.
1.0.1
8.4.7
16.16.0
No response
[ ] Regression
[x] Bug report
[ ] Feature request
[ ] Documentation issue or request
[ ] Support request => Please do not submit support request here, instead post your question on Stack Overflow.
Due to a server that requires a cookie (will attempt to set the cookie and redirect, resulting in an infinite loop), I need to add cookies support to Axios. The consensus appears to be that this is best accomplished through the axios-cookiejar-support package at https://github.com/3846masa/axios-cookiejar-support
This is done by pushing the Axios instance through an axiosCookieJarSupport()
wrapper.
All requests to this.httpService.get()
fail, with the message "TypeError: Cannot read property 'request' of undefined"
Would expect this.httpService.get()
to work.
It does not.
import { Process, Processor } from '@nestjs/bull'
import { HttpService } from '@nestjs/axios'
import { Job } from 'bull'
import axiosCookieJarSupport from 'axios-cookiejar-support'
import { CookieJar } from 'tough-cookie'
@Processor('scrapeBot')
export class ScrapeBot {
constructor(
private readonly httpService: HttpService,
) {}
@Process('getPage')
async handleGetPage(job: Job) {
axiosCookieJarSupport(this.httpService.axiosRef)
const jar = new CookieJar()
const query = this.httpService.get(job.data.url, { withCredentials: true, jar })
// fails at this point
}
}
Nest version: 8.0.6
For Tooling issues:
- Node version: 16.4.0
- Platform: Mac
.get()
request.this.httpService.axiosRef
, but I can't guess what.Instead of a plain json type, I'd like to have an object instance from the http response.
Just integrate plainToInstance
before returning the response observable.
No response
The usecase is everywhere you want logic into classes.
no
No response
服务运行一段时间之后会出现该问题,接口响应时间随运行时间而变长
0.0.7
8.0.0
14.17.3
No response
How do I register the axios httpmodule module globally?
@Module({
imports: [
HttpModule.register({
timeout: 5000,
maxRedirects: 5,
httpsAgent: new Agent({
rejectUnauthorized: false
}),
transformResponse: [
function (data) {
// Dols whatever you want to transform the data
return _json.parse(data);
}
]
})
],
providers: [RequestService],
exports: [RedisService]
})
expor
No response
Easy to call
[Nest] 13372 - 12/10/2022 03:21:02 ERROR [ExceptionsHandler] self signed certificate in certificate chain
Error: self signed certificate in certificate chain
at TLSSocket.onConnectSecure (node:_tls_wrap:1530:34)
at TLSSocket.emit (node:events:520:28)
at TLSSocket._finishInit (node:_tls_wrap:944:8)
at TLSWrap.ssl.onhandshakedone (node:_tls_wrap:725:12)
none
async getPdfBase64(fileData: string, fileJasper: string, parameters: string) {
const url = "https://localhost:3014/jasper/";
const data = JSON.stringify({ "fileData": fileData, "fileJasper": fileJasper, "parameters": parameters });
console.log(data)
var value = await lastValueFrom(
this.httpService.post(url, data).pipe(map((resp) => resp.data))
);
return value;
}
i want to consume an https api using nestjs/axios
0.1.0
8
16.14.0
No response
This could happen when you perform request to 3rd party service which supports Brotli compression axios/axios#5346
Any http request to 3rd party like instagram/facebook api will return Error: unexpected end of file
Successful response
1.0.1
8.1.3
16.18.0
No response
Hi!
When using the package, I constantly encounter problems:
Therefore, I constantly need to do some actions when using methods from HTTPService.
I would like to be able to pass options for the retry and interceptors at once when initializing HttpModule.
Example with retries:
export type RetryOptions = {
retryableStatuses: number[]; // statuses under which the retry will be made
retryableCodes: string[]; // codes under which the retry will be made
limit: number; // limit of retries
delay: number; // delay for retry
}
export type HttpModuleOptions = {
axiosConfig: AxiosRequestConfig;
retryOptions?: RetryOptions;
};
export class HttpService {
constructor(@Inject(RETRY_OPTIONS) private readonly retryOptions: RetryOptions | undefined) {}
request<T = any>(config: AxiosRequestConfig): Observable<AxiosResponse<T>> {
const obs = this.makeObservable<T>(this.instance.request, config);
return this.makeRetryableRequest(obs);
}
protected makeRetryableRequest<TResponseData = unknown>(
response: Observable<AxiosResponse<TResponseData>>
): Observable<AxiosResponse<TResponseData>> {
if (this.retryOptions === undefined) {
return response;
}
return response.pipe(rxjs.retry({ delay: ..., count: ... })).
}
}
Example with interceptors:
export type Interceptor = {
onFulfilled: (value: any) => any;
onRejected: (error: any) => any;
options?: AxiosInterceptorOptions;
}
export type HttpModuleOptions = {
axiosConfig: AxiosRequestConfig;
axiosInstanceInterceptors?: { response: Interceptor[] };
};
export class HttpService {
constructor(
@Inject(AXIOS_INSTANCE_TOKEN)
protected readonly instance: AxiosInstance = Axios,
@Inject(AXIOS_INSTANCE_INTERCEPTORS)
private readonly interceptors: Interceptor[],
) {
this.interceptors.forEach(interceptor => {
instance.response.use(interceptor.onFulfilled, interceptor.onRejected, interceptor.options);
});
}
}
No response
When initializing the module, I want to immediately set everything that is necessary to work with axios :)
I specified the use cases in the problems.
Hi. This repo use a dependency that use a dependency that contains a security issue.
@nestjs/[email protected] > [email protected] > [email protected]
.
Solve that security issue is easy, just updated to Axios 1.6.8 https://github.com/axios/axios/releases/tag/v1.6.8
Details about the security issue: GHSA-cxjh-pqwp-8mfp
https://github.com/nestjs/axios
I expect no contain any security issue on the dependencies of @nestjs/axios
3.0.2
10.3.9
18.16
No response
this library does not support Nestjs 10.0.0
this library does not support Nestjs 10.0.0
No response
this library does not support Nestjs 10.0.0
2.0.0
10.0.0
18.16.0
this library does not support Nestjs 10.0.0
HTTP Wiki states that the DELETE method should have an optional payload. Why is this not the case?
add data: {}` as a optional argument to delete method.
No response
Write now, i cannot use this library to delete a resource from the api.
Currently axios has a moderate level vulnerability that without updating the lib @nestjs/axios we can only resolve it with npm audit fix --force, which is not a good practice
axios 1.0.0 - 1.5.1
Severity: moderate
Axios Cross-Site Request Forgery Vulnerability - GHSA-wf5p-g6vw-rhxx
fix available via npm audit fix --force
Will install [email protected], which is outside the stated dependency range
node_modules/axios
Update axios for version 1.6.0
This modification is necessary because without it many applications are left with vulnerabilities, this affects all teams that use these libs
This issue lists Renovate updates and detected dependencies. Read the Dependency Dashboard docs to learn more.
These updates have all been created already. Click a checkbox below to force a retry/rebase of any.
package.json
@commitlint/cli 19.3.0
@commitlint/config-angular 19.3.0
@nestjs/common 10.3.10
@nestjs/core 10.3.10
@nestjs/platform-express 10.3.10
@nestjs/testing 10.3.10
@types/jest 29.5.12
@types/node 20.14.12
@typescript-eslint/eslint-plugin 7.17.0
@typescript-eslint/parser 7.17.0
axios 1.7.2
eslint 8.57.0
eslint-config-prettier 9.1.0
eslint-plugin-import 2.29.1
husky 9.1.1
jest 29.7.0
lint-staged 15.2.7
prettier 3.3.3
reflect-metadata 0.2.2
release-it 17.6.0
rimraf 6.0.1
rxjs 7.8.1
ts-jest 29.2.3
typescript 5.5.4
@nestjs/common ^7.0.0 || ^8.0.0 || ^9.0.0 || ^10.0.0
axios ^1.3.1
rxjs ^6.0.0 || ^7.0.0
No response
Nest 7 > 8
We have recently bumped NestJS from 7 to 8.
The migration guide states:
The
HttpModule
exported from the@nestjs/common
package has been deprecated and will be removed in the next major release. Instead, please use the@nestjs/axios
package (otherwise, there are no API differences).
Note:
(otherwise, there are no API differences)
However, with @nestjs/axios
we get a deprecation warning for toPromise()
:
Note that this deprecation is due to changes to the RxJS API - not NestJS.
Our code is promise based.
With toPromise()
being deprecated, we are left with an Observable
- this is quite a big API change!
Although I'm sure there's a good reason for this, I'm not sure why methods like get
or post
will have an Observable
API - these operations seem to me, for the consumer at least, more of a success
or failure
case, rather than a stream case.
From their About:
Promise based HTTP client for the browser and node.js
It's odd to have an Observable
API from @nestjs/axios
where axios
is promise based.
Other than having to change a lot of instances of toPromise()
, it is not clear what is the recommended solution here.
As the RxJS docs state you need to choose between lastValueFrom
or firstValueFrom
. But which one? The model is broken here, we just want to send a request and await the response - no streams involved.
Alternatively, some SO answers suggest the following (which doesn't seem to work, by the way):
return this.http.get(this.DATA_URL).pipe(
map((axiosResponse: AxiosResponse) => {
return axiosResponse.data;
})
);
To summarise:
Bump to NestJS 8 per migrate guide. See warning in IDE.
this.httpService.get(serviceUrl).toPromise();
@nestjs/axios
should provide promise-based API.
No response
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.