502 when calling an external API
therealafter
FREEOP

10 months ago

On localhost it works perfectly but on railway when I try to call the external g2a service it returns a 502

  @IsPublic()
  @Post('order')
  async createOrder() {
    const token = await this.g2aService.generateOAuthToken();

    try {
      const response = await axios.post(
        'https://api.g2a.com/v1/order',
        {
          product_id: '10000510379001',
          max_price: 3,
          currency: 'BRL',
        },
        {
          headers: {
            Authorization: `Bearer ${token.accessToken}`,
            'Content-Type': 'application/json',
          },
          timeout: 50000, // 50 second timeout
        },
      );

      return response.data;
    } catch (error) {
      console.log(error);
      console.error('G2A API Error:', error.response?.data || error.message);
      return error;
    }
  }

---------
my main.ts

// main.ts
import './domain/services/discord';

import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module';

import { Logger, ValidationPipe } from '@nestjs/common';
import HttpExceptionFilter from './infrastructure/exception/http-exception.filter';
import webpush from 'web-push';
import { AllExceptionsFilter } from './infrastructure/exception/all-exceptions.filter';
import helmet from 'helmet';
import { Request, Response, NextFunction } from 'express';

const PORT = process.env.PORT || 8080;

async function bootstrap(): Promise<void> {
  const app = await NestFactory.create(AppModule, {
    logger: ['verbose', 'debug', 'log', 'warn', 'error'],
  });

  // Enable CORS globally
  app.enableCors({
    origin: '*',
    methods: ['GET', 'POST', 'PUT', 'DELETE', 'OPTIONS', 'PATCH'],
    allowedHeaders: ['Content-Type', 'Authorization', 'X-API-Key'],
  });

  app.use(helmet());

  // Middleware to listen for aborted requests
  app.use((req: Request, res: Response, next: NextFunction) => {
    req.on('aborted', () => {
      console.warn('Request aborted by the client');
      // Optional: Cleanup logic here
    });
    next();
  });

  // Global error handling middleware for aborted request error
  app.use((err: any, req: Request, res: Response, next: NextFunction) => {
    if (err.name === 'BadRequestError' && err.message === 'request aborted') {
      console.warn('Caught request aborted error:', err);
      res.status(499).send('Client Closed Request'); // 499 status code for client abort
    } else {
      next(err);
    }
  });

  app.useGlobalFilters(new AllExceptionsFilter(), new HttpExceptionFilter());

  app.useGlobalPipes(
    new ValidationPipe({
      transform: true,
      always: true,
      forbidNonWhitelisted: true,
    }),
  );

  try {
    const server = app.getHttpServer();
    // Increase server timeout (adjust timeout as needed)
    server.setTimeout(120000); // 2 minutes

    server.keepAliveTimeout = 65000;
    server.headersTimeout = 66000;

    await app.listen(PORT, '0.0.0.0');

    webpush.setVapidDetails(
      'mailto: <teste@gmail.com>',
      process.env.VAPID_PUBLIC_KEY,
      process.env.VAPID_PRIVATE_KEY,
    );

    Logger.log(`Server running on http://localhost:${PORT}`, 'Bootstrap');
  } catch (err) {
    console.error(err);
  }
}

bootstrap();
$10 Bounty

2 Replies

Railway
BOT

10 months ago

Hey there! We've found the following might help you get unblocked faster:

If you find the answer from one of these, please let us know by solving the thread!


therealafter
FREEOP

10 months ago

just in axios request


Welcome!

Sign in to your Railway account to join the conversation.

Loading...