Using fetch to get a simple string

Viewed 8571

So I have this in my API:

router.get('/assetName', function(req, res, next){
  //Get the token from the cookies
  var token = req.cookies.access_token;
  //Check it with the config secret
  if(jwt.verify(token, config.secret)){
    //find from name in the request body
    User.find({_id: req.query.id}).then(function(users){
      var z;
      var name = [];
      var assetHolder = users[0].assets;
      for(z=0; z < assetHolder.length; z++){
        if(assetHolder[z]._id == req.query.vid){
          name = assetHolder[z].name;
        }
      }
      console.log(name);
      res.send(name);

      //Error handling
    }).catch((err) => console.error(err));
  }else{
    res.send("Unauthorized");
  }
});

The name variable is been printed to to console and look like this:

Asset1Name
Asset2Name

I am using the fetch request below:

      var vehiclesT = asset.assetIDs;
      if(!asset.assetIDs){
        vehiclesT = [];
      }
      var y;
      var assets = [];
      for(y=0; y< assetsTemp.length; y++){
        var url = 'api/assetName/?vid='+assetsTemp[y]+'&id='+id;
        fetch(url, {credentials: 'include', method: 'get'}).then(function(data){
          console.log(data);
          vehicles.push(data);
        });
      }

But temp is been printed as:

Response {type: "basic", url: "http://localhost:4000/api/assetName/?vid=f4ufh49h49fh9fh94fh94hf&id=f484fh48fhfh98fh489fh", redirected: false, status: 200, ok: true…}

And so the vehicles array is empty.

Why is this and how can I get the value printed to the console in the API with fetch(or another better method)?

Thanks, Ed.

1 Answers
Related