2017-08-01 11 views
1

を取得するにはfetchの使い方:だから私は私の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"); 
    } 
}); 

名前の変数がコンソールと次のように見えるようにするために印刷されている。

Asset1Name 
Asset2Name 

私が使用しています下のフェッチ要求:

 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); 
     }); 
     } 

しかし、一時は次のように印刷されている。

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

したがって、車両の配列は空です。

これはなぜ、fetch(または他のより良い方法)を使用してAPIのコンソールに値を表示するのですか?

ありがとう、エド。

答えて

1

あなた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); 
}); 

は、最初約束はすぐに適切なフォーマットでデータをあなたを与えるものではありません。実際にはResponse objectがあります。希望する形式(Blob、JSON、arrayBufferなど)に対応するメソッドを呼び出す必要があります。

この場合、あなたは使用することができますResponse.text()

関連する問題