首页 > 解决方案 > 具有本机反应的 Axios 不返回文档并崩溃应用程序

问题描述

编辑

好的,所以我的方法很好。出于某种原因,当我更改const response = await...const res = await..(或除“响应”之外的任何其他名称)时,它起作用了。如果这不是内存泄漏,那么我不知道这到底是什么。如果有人有任何见解,我将不胜感激。


我正在向我的客户提出请求:

const config = { headers: { "Content-Type": "application/json" } };

const data = JSON.stringify({ postId });

console.log('sending request'); // prints

const response = await axios.post(
  `http://${GATEWAY}:5000/api/posts/single`,
  data,
  config
);

console.log("response received"); // never reached

但从request received不打印。

我的后端路线有这个,

const post = await Post.findById(postId).populate("likes");

console.log(post); // prints post

return res.json(post);

它会适当地找到帖子并将其记录到控制台。我不确定发生了什么事。任何地方都不会打印任何错误,并且应用程序会在一段时间后崩溃。应该是在等回复吧。

另外,当我这样做时

return res.json(null)

我的客户收到回复。但是当我尝试返回时,post或者即使我尝试返回

return res.json( { msg: "Hello World" } );

它挂起。

此外,我在整个应用程序中执行类似的 axios 请求——它们按预期工作和运行。不知道我在这里做错了什么。

我什至试过,

const response = await axios.get(
  `http://${GATEWAY}:5000/api/posts/${postId}`,
);

但它的行为和失败方式相同。如果我让请求挂起太久,应用程序就会放弃并崩溃。

请注意,另外,我正在使用axios而不是axios-react-native

标签: node.jsreactjsmongodbreact-nativeaxios

解决方案


你确定它是“http”而不是“https”
或者
尝试:

const url = `${apiBaseUrl}/someUrlText/someUrlText/`;
const headers = {headers: { "Content-Type": "application/json"}};
const body = JSON.stringify({ postId });
axios
.post(url, body, headers)
.then(res => {
  console.log("request received",res);
})
.catch(err => console.log("TODO: Handle error axios", err));

推荐阅读