Home > Enterprise >  Why I cannot send a string in send in express?
Why I cannot send a string in send in express?

Time:02-14

I have the following code to get data from an external API:

const axios = require('axios');
const express =  require('express');

const app = express()

app.get("/coins", (req, res) => {
    console.log("/coins test");

    axios.get("https://www.cryptingup.com/api/markets")
       .then(resultat=>{
         console.log(resultat.data.markets)
           res = resultat.data.markets
           myS="";

               res.forEach(element=>{
               console.log(element.exchange_id);
               myS=myS element.exchange_id;
            });

            res.send(myS);
         
       })
       .catch(error => console.log(`error is ${error}`));
})

port = 3000

app.listen(port, ()=>{console.log(`The server has started and is listening on port number: ${port}`);});

when I execute the code I get the following:

error is TypeError: res.send is not a function

I dont know where is my error.

CodePudding user response:

You've overwritten the value of res that was passed into the function with this line of code:

res = resultat.data.markets

So, after doing that the original res is gone so you can't call res.send() any more.

Define your own separately named variable:

app.get("/coins", (req, res) => {
    console.log("/coins test");

    axios.get("https://www.cryptingup.com/api/markets")
       .then(resultat => {
           console.log(resultat.data.markets);
           let markets = resultat.data.markets;
           let myS = "";

           markets.forEach(element => {
               console.log(element.exchange_id);
               myS = myS   element.exchange_id;
           });

           res.send(myS);
         
       })
       .catch(error => console.log(`error is ${error}`));
})

Also, you must declare all variables you use with let or const.


FYI, you could simplify a bit with:

let myS = resultat.data.markets.map(element => element.exchange_id).join("");
res.send(myS);

CodePudding user response:

Your problem is that you are grabbing the "res" object which is passed into the express callback function, but then for whatever reason you reassign it to equal some results from your axios call, essentially removing all of the Express methods on "res".

  • Related