2017-08-01 44 views
1

所以我在我的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); 
     }); 
     } 

但将temp被打印为:

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()

相关问题