1

I have an express server with one route. When I call this route in my browser I am able to get data sent by my server. However when I try to call this route from script with a simple node-fetch I have an response but my route is not called (not data retrieved). I explain :

Here the code of my express server:

App.ts

import express from "express";
import httpServer from "./httpServer";
import HttpRoutes from "./httpRoutes";

class BrokerServer {
  public httpServer!: express.Application;
  public httpRoutes!: HttpRoutes;

  constructor() {
    this.initHttpServer();
  }

  private initHttpServer(): void {
    this.httpServer = httpServer;
    this.httpRoutes = new HttpRoutes();
    this.httpRoutes.routes();
  }
}

new BrokerServer();

Server.ts

import express from "express";
import * as bodyParser from "body-parser";

class HttpServer {
  public HTTP_PORT: number = 9000;
  public server!: express.Application;

  constructor() {
    this.server = express();
    this.server.use(bodyParser.json());

    this.server.listen(this.HTTP_PORT, () => {
      console.log('Broker HTTP Server listening on port 9000');
    });
  }
}

export default new HttpServer().server;

And my routes.ts

import httpServer from "./httpServer";

export default class HttpRoutes {
  public routes(): void {
    httpServer.get("/getNodes", (req, res) => {
      console.log("GET");
      res.status(200).send(JSON.stringify({ nodes: [] }));
    });
  }
}

When I launch my server and naviguate on the url http://localhost:9000/getNodes I can see my console.log('GET'). this is not the case when I try with node-fetch.

Here my little script:

const fetch = require('node-fetch');

console.log('launch fetch');

fetch('http://localhost:9000/getNodes')
.then(response => {
    console.log('response', response);
    return response.json()
})
.then(results => {
    console.log('results', results);
})
.catch(error => {
    console.log('error', error);
});

With the script I reach the console.log('response', response); but never my results.

Anyone knows where is the problem ?

onedkr
  • 3,226
  • 3
  • 21
  • 31

1 Answers1

0

I found why it didn't work. I used a ramdom port (port 9000) which is already used. Changed the port works...

onedkr
  • 3,226
  • 3
  • 21
  • 31