获取请求返回状态 cors 和可读流

Jul*_*kin 2 javascript http fetch

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

\n\n

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

\n\n

然后这是我在后端发送呼叫的路线

\n\n

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

\n\n

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

\n\n

\r\n
\r\n
{ __v: 0,\r\n  updatedAt: 2018-10-19T15:47:16.809Z,\r\n  createdAt: 2018-10-19T15:47:16.809Z,\r\n  recipeId: \'http://www.edamam.com/ontologies/edamam.owl#recipe_7dae4a3b1f6e5670be3c2df5562e4782\',\r\n  owner: 5bc9fc6a3682194cdb8d6fa5,\r\n  _id: 5bc9fc843682194cdb8d6fa7 }
Run Code Online (Sandbox Code Playgroud)\r\n
\r\n
\r\n

\n\n

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

\n\n

\r\n
\r\n
Response {type: "cors", url: "http://localhost:4741/recipes", redirected: false, status: 201, ok: true, \xe2\x80\xa6}\r\nbody: ReadableStream\r\nbodyUsed: true\r\nheaders: Headers {}\r\nok: true\r\nredirected: false\r\nstatus: 201\r\nstatusText: "Created"\r\ntype: "cors"\r\nurl: "http://localhost:4741/recipes"\r\n__proto__: Response
Run Code Online (Sandbox Code Playgroud)\r\n
\r\n
\r\n

\n\n

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

\n

Jul*_*tta 7

由于您用于fetch发出请求,因此响应被封装在Response对象中,并且要访问它,您必须调用 async 方法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);
Run Code Online (Sandbox Code Playgroud)

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

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

更新

另一种方法是:

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

  console.log(response);
})();
Run Code Online (Sandbox Code Playgroud)

我希望这有帮助。