使用提取获取简单的字符串 [英] Using fetch to get a simple string

查看:109
本文介绍了使用提取获取简单的字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我的API中有这个

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

name变量已打印到控制台,如下所示:

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

但是温度打印为:

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

因此,车辆数组为空.

这是为什么,如何通过fetch(或其他更好的方法)将值打印到API中的控制台上?

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

谢谢Ed.

推荐答案

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

如您所见,第一个 Promise 并不能立即为您提供格式正确的数据;实际上,它为您提供了一个响应对象,您需要在该对象上以所需的格式(Blob,JSON,arrayBuffer等)调用相应的方法

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

在这种情况下,您提到您期望的是文本,因此可以使用Response.text()

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

这篇关于使用提取获取简单的字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆