0
votes

Error

POST http://localhost:3000/api/user 504 (Gateway Timeout)

ERROR Server Error Code: 504 Message: Http failure response for http://localhost:3000/api/user: 504 Gateway Timeout

Description

I am getting a 504 (Gateway Timeout) error when running this code on a device. The POST request works if running with with "ng serve" on 4200. The request also works if running with "http-server -p 8080 -c-1 dist/test504" on 8080 and testing with browser. I only get the 504 error when running with http-server and testing through an Android device, using Chrome (so I can inspect what is going on). I imagine the difference is the Service Worker is proxying the call, but that's not helping me figure it out. Also, tested API directly with Postman and it works fine.

One thing to note is that the 504 error happens sub-second. It doesn't seem like it's waiting for anything. It just times out immediately.

I've created a simplified front and back-end, which still has the issue.

Angular app.compoment.ts

saveUser() calls a Node JS/Express API running on localhost:3000.

import { Component } from '@angular/core';
import { HttpClient} from '@angular/common/http';
import { Iuser } from './user';
import { catchError } from 'rxjs/operators';
import { throwError} from 'rxjs';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})

export class AppComponent {
  user: Iuser = {
    email: '',
    firstName: ''
  };
  result: any;

  constructor(private http: HttpClient) {}

  saveUser() {
    let nbr: number;
    let email: string;

    nbr = Math.floor(Math.random() * Math.floor(100));
    email = 'email' + nbr + '@gmail.com';
    this.user.email = email;
    this.user.firstName = 'test';
    console.log('user=', this.user);

    this.postUser(this.user)
    .pipe(
      catchError (this.handleError)
    )
    .subscribe(data => {
      console.log('result=', data);
      this.result =  JSON.stringify(data);
    });
  }

  private postUser(user: Iuser) {
    return this.http.post('http://localhost:3000/api/user', user);
  }

  private handleError(error) {
    let errorMessage = '';
    if (error.error instanceof ErrorEvent) {
        // client-side error
        errorMessage = `Client Error: ${error.error.message}`;
    } else {
        // server-side error
        errorMessage = `Server Error Code: ${error.status}\nMessage: ${error.message}`;
    }
    return throwError(errorMessage);
  }
}

Node JS/Express API

const express = require('express');
const bodyParser = require('body-parser');
const mongoose = require('mongoose');

const User = require('./models/user');

const app = express();

mongoose.connect(process.env.MONGO_CONNECT)
  .then(() => {
    console.log('Connected to database');
  })
  .catch(() => {
    console.log('Connection failed');
  });

app.use(bodyParser.json());

app.use((req,res, next) => {
  res.setHeader('Access-Control-Allow-Origin', process.env.CORS_ORIGIN);
  res.setHeader('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept');
  res.setHeader('Access-Control-Allow-Methods', 'GET, POST, PATCH, DELETE, OPTIONS');
  next();
});


app.post('/api/user', (req, res,next) => {
  const user = new User({
    firstName: req.body.firstName,
    email: req.body.email
  });
  console.log(user);
  user.save();
  res.status(201).json({
    message: 'Post added successfully'
  });
});

module.exports = app;

Versions

Package                           Version
-----------------------------------------------------------
@angular-devkit/architect         0.803.22
@angular-devkit/build-angular     0.803.22
@angular-devkit/build-optimizer   0.803.22
@angular-devkit/build-webpack     0.803.22
@angular-devkit/core              8.3.22
@angular-devkit/schematics        8.3.22
@angular/cli                      8.3.22
@angular/pwa                      0.803.22
@ngtools/webpack                  8.3.22
@schematics/angular               8.3.22
@schematics/update                0.803.22
rxjs                              6.5.4
typescript                        3.5.1
webpack                           4.39.2

Node JS version is 12.13.1
1
Can you update with the code who starts the server?rpereira15
rpereira15, this is all on my machine in the development environment so I start the server. When I run it from my machine using a browser instead of from my device, the code goes all the way through to the API and database.DevReboot
Correction. When I use http-server and port 8080, service worker is being used whether in browser or from device through Chrome dev tools. I've looked at the service worker code to compare device vs. browser and can't see any difference. Both requests look the same and are calling the same local server (localhost:3000), but the device can't seem to access localhost:3000. Any help or ideas would be appreciated.DevReboot

1 Answers

1
votes

I figured this out. The problem is that I had to add an additional rule in Chrome dev remote devices tools to port-forward localhost:3000, which the web site is using. Because I didn't have that, when running on the device, it was looking for localhost:3000 to be on the device, not my desktop where localhost:3000 Node / Express was running.