【问题标题】:Fetch request returning status cors and readable stream获取返回状态cors和可读流的请求
【发布时间】:2018-10-24 21:00:30
【问题描述】:

我正在对我的后端进行 fetch 调用,这是调用。

    const response = await fetch(apiUrl + '/recipes', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        'Authorization': `Token token=${user.token}`
      },
      body: JSON.stringify({
        recipe: {
          recipeId: uri
        }
      })
    })

那么这就是我在后端发送呼叫的路由

router.post('/recipes', requireToken, (req, res) => {
  req.body.recipe.owner = req.user.id
  Recipe.create(req.body.recipe)
    .then(recipe => {
      console.log('Recipe object saved is', recipe)
      res.status(201).json({ recipe: recipe.toObject() })
    })
    .catch(err => handle(err, res))
})

当我这样做时,正确的对象会在它发回之前记录下来。这是记录的示例

{ __v: 0,
  updatedAt: 2018-10-19T15:47:16.809Z,
  createdAt: 2018-10-19T15:47:16.809Z,
  recipeId: 'http://www.edamam.com/ontologies/edamam.owl#recipe_7dae4a3b1f6e5670be3c2df5562e4782',
  owner: 5bc9fc6a3682194cdb8d6fa5,
  _id: 5bc9fc843682194cdb8d6fa7 }

但是,当我 console.log 我在前端返回的内容时,我得到了这个。

Response {type: "cors", url: "http://localhost:4741/recipes", redirected: false, status: 201, ok: true, …}
body: ReadableStream
bodyUsed: true
headers: Headers {}
ok: true
redirected: false
status: 201
statusText: "Created"
type: "cors"
url: "http://localhost:4741/recipes"
__proto__: Response

在通话中,它会使用我的数据库记录操作,因此信息会被保存,并在应该发回之前被记录下来,但是不会发回正确的信息。 提前感谢您的任何回复。

【问题讨论】:

    标签: javascript http fetch


    【解决方案1】:

    由于您使用fetch 发出请求,因此响应被封装在Response 对象中,要访问它,您必须调用异步方法json()。就像下面这样:

    const Response = await fetch(apiUrl + '/recipes', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        'Authorization': `Token token=${user.token}`
      },
      body: JSON.stringify({
        recipe: {
          recipeId: uri
        }
      })
    });
    
    const json = await Response.json();
    console.log(json);
    

    您可以在 chrome 控制台中使用另一个示例。

    (async () => {  
      const Response = await fetch('https://jsonplaceholder.typicode.com/todos/1');
      const res = await Response.json();
      console.log(res);
    })();
    

    更新

    另一种方法是:

    (async () => { 
      const response = await (
        await fetch('https://jsonplaceholder.typicode.com/todos/1')
      ).json();
    
      console.log(response);
    })();
    

    我希望这会有所帮助。

    【讨论】:

    • 感谢您的回复!我尝试了 .json(),但无法让它工作。我假设我还在做一些愚蠢的事情。我最终切换到了 axios 调用,这就像一个冠军。
    猜你喜欢
    • 1970-01-01
    • 2021-05-28
    • 2014-10-19
    • 2011-03-03
    • 2016-09-29
    • 2012-03-09
    • 1970-01-01
    • 2015-12-08
    • 2022-10-05
    相关资源
    最近更新 更多