Devsterefic
Devsterefic

Reputation: 513

res.send is not a function

I am making an api call and recieving the data, however, I am having trouble sending the data back to my js file. I tried using res.send but I am getting an error. I can't seem to figure out how to send the information back to the javascript file. (I took my key out of the request link. For security reasons, however, I am getting the data back from the api call). The only problem I am having is returning the data to the frontend javascript file.

This is the Javascript file that sends the original request:

/ ********** options button function makes api call to get selected cities forecast *****************

function getCityForecast(e){


     var id = document.getElementById('cities');
     var getValue = id.options[id.selectedIndex].value;
     var suffix = getValue + ".json";

     var newObj = JSON.stringify({link : suffix});

     var xhr = new XMLHttpRequest();

     xhr.open("POST", "http://localhost:3000/", true);
     xhr.setRequestHeader("Content-Type", "application/json;charset=UTF-8");
     xhr.send(newObj);

     xhr.onreadystatechange = function(){
         if(xhr.readyState === 4){
             console.log(xhr.response);
             console.log('recieved');
         } else {
             console.log('error');
         }
     }
}

My server.js file looks like this:

var express = require('express');
var app = express();
var bodyParser = require('body-parser');
var http = require('http');
var path = require('path');
var request = require('request');


// ****************** Middle Ware *******************
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());

app.use(express.static(__dirname + '/public'));



var retrievedString;
// **************** Post Request *******************
app.post('/', function(req, res){

var link = "http://api.wunderground.com/api/key/forecast";
retrievedString = link.concat(req.body.link);

request = http.get(retrievedString , function(res){
    var body = '';

    res.on('data', function(data){
         body += data;      
    });

    res.on('end', function(){
        var parsed = JSON.parse(body);
        console.log(parsed.forecast.txt_forecast);
        res.send(parsed.forecast.txt_forecast);
    });
})

    .on('error', function(e) {
        console.log("Got error: " + e.message);
    });
});

app.listen(3000, function() { console.log('listening')});

Upvotes: 1

Views: 10208

Answers (1)

SylonZero
SylonZero

Reputation: 1207

You are overloading the definition of the variable res which is also what you called the response variable for your Express route handler method. In the callback function of the request, use a different name for that variable - for example:

request = http.get(retrievedString , function(resDoc){

Upvotes: 8

Related Questions