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

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

问题描述

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

但是 temp 被打印为:

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…}

所以车辆数组是空的.

这是为什么,我如何使用 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)?

谢谢,埃德.

推荐答案

您在 fetch 中遗漏了一个步骤:

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

如您所见,第一个 Promise 并没有立即以正确的格式提供数据;它实际上为您提供了一个 Response 对象,您需要在该对象上调用对应的方法到你想要的格式(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()

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

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