Sending/handling GET requests in typescript using Express, Request and Node.js

annedroiid picture annedroiid · Jul 21, 2016 · Viewed 15.9k times · Source

I'm using a combination of Express and Request (installed using npm) to try to send a get request to get some json from the server. However no matter what I do the body that is returned is "undefined".

This is the code in my server.js file. The json isn't actually what I'm sending, it's just an example as I can't post what I'm actually sending.

import express = require("express");
import bodyParser = require("body-parser");
let app = express();
app.use(bodyParser.json());

app.get('/config', function(req, res){
    res.json('{name: test}');
})

app.listen(3000);

I've tried both of the following but both of them say that body is undefined.

import request = require("request");

let req = {
    url: `http://localhost:3000/config`,
    method: 'GET',
    headers: {
        'Content-Type': 'application/json'
    }
}

request(req, function(error, response, body){
    this.config = JSON.parse(body);
})

request(`/config`, function(err, res, body) {
    this.config = JSON.parse(body);
});

Does anyone know what I'm doing wrong? I've never used express or request before so any tips would be greatly appreciated.


UPDATE

If I change the request code to the following, the inside of the function is never run. Does anyone know why this would be?

let req = {
    url: `http://localhost:3000/config`,
    method: 'GET',
    headers: {
        'Content-Type': 'application/json'
    }
}

request(req, function(error, response, body){
    console.log("response => "+JSON.parse(body));
    return JSON.parse(body);
})

Answer

Samuel Toh picture Samuel Toh · Jul 21, 2016

Since OP hasn't got it working and I believe the code he got up there is correct. I may as well post my working solution here to help him get started.

Hopefully this will save you hours of debugging...

Client:

"use strict";
let request = require("request");

let req = {
    url: `localhost:4444/config`,
    proxy: 'http://localhost:4444',
    method: 'GET',
    headers: {
        'Content-Type': 'application/json'
    }
};

request(req, function (err, res, body) {
    this.config = JSON.parse(body);
    console.log("response => " + this.config);
});

Server:

"use strict";
var express = require("express");
var bodyParser = require("body-parser");
var app = express();
var config = require('config');
app.use(bodyParser.json());

app.get('/config', function(req, res){
    res.json('{name: test}');
});

// Start the server
app.set('port', 4444);

app.listen(app.get('port'), "0.0.0.0", function() {
    console.log('started');
});

Output:

response => {name: test}