Ed Lynch
Ed Lynch

Reputation: 623

Using fetch to get a simple string

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.

Upvotes: 6

Views: 14258

Answers (1)

jonathanGB
jonathanGB

Reputation: 1540

You are missing one step in your fetch:

fetch(url, {
  credentials: 'include',
  method: 'get'
})
.then(function(body){
  return body.text(); // <--- THIS PART WAS MISSING
}).then(function(data) {
  console.log(data);
  vehicles.push(data);
});

As you can see, the first Promise doesn't give you right away the data in the right format; it in fact gives you a Response object, on which you need to call the corresponding method to the format you desire (Blob, JSON, arrayBuffer, etc.)

In this case, you mentioned that what you expect is text, therefore you can use Response.text()

Upvotes: 21

Related Questions