我在尝试使用 axios 发送发布请求时遇到网络错误。
错误: 网络错误 在 node_modules\axios\lib\core\createError.js:15:17 in createError 在 node_modules\axios\lib\adapters\xhr.js:81:22 中的 handleError 在 node_modules\event-target-shim\dist\event-target-shim.js:818:20 在 EventTarget.prototype.dispatchEvent 在 node_modules\react-native\Libraries\Network\XMLHttpRequest.js:600:10 在 setReadyState 在 __didCompleteResponse 中的 node_modules\react-native\Libraries\Network\XMLHttpRequest.js:395:6 在 node_modules\react-native\Libraries\vendor\emitter\EventEmitter.js:189:10 在发射 在 __callFunction 中的 node_modules\react-native\Libraries\BatchedBridge\MessageQueue.js:416:4 在 __guard$argument_0 中的 node_modules\react-native\Libraries\BatchedBridge\MessageQueue.js:109:6 在 __guard 中的 node_modules\react-native\Libraries\BatchedBridge\MessageQueue.js:364:10 在 node_modules\react-native\Libraries\BatchedBridge\MessageQueue.js:108:4 在 callFunctionReturnFlushedQueue at [native code]:null in callFunctionReturnFlushedQueue
代码:
const [state, setTest] = useState({data: null});
const[isLoading, setLoading] = useState(true);
const {testowy} = require("./clientRequests/Creq_lib");
// testowy().then(data => setState({data: data})).catch(error => {console.log(error)}); This one doesn't work
useEffect(() => {
// axios.post("http://192.168.0.4:8080/testowy").then(res => {setTest({data: res.data}); setLoading(false);}); This works ok
// testowy().then(res => {setTest({data: res}); setLoading(false);});
testowy().then(res => {setTest({data: res}); setLoading(false);}); // These two don't work
}, []);
当直接使用 axios.post() 时一切正常,但在我尝试导入一个函数后,它应该做同样的事情我得到这个网络错误。
具有上述功能的库:
const {Creq_testowy} = require("./Creq_testowy");
module.exports={
testowy: Creq_testowy,
}
函数本身:
const axios = require("axios");
function Creq_testowy() {
return new Promise((resolve, reject) => {
axios.post(`http://192.168.0.4:8080/testowy`)
.then(res => {
console.log(res.data);
resolve(res.data);
})
.catch(error => {console.log(error)})
});
}
module.exports = {
Creq_testowy,
}
为什么直接使用 axios.post() 一切正常? 为什么我在使用导入的函数时会收到这个错误?
答案 0 :(得分:1)
为什么在 axios 已经返回一个承诺时创建一个承诺? 你可以试试这个吗?
async function Creq_testowy() {
const res = await axios.post(`http://192.168.0.4:8080/testowy`)
return res.data;
}
或者这个
async function Creq_testowy() {
try {
const res = await axios.post(`http://192.168.0.4:8080/testowy`)
return res.data;
} catch(err) {
console.log(err);
}
}
您是否在本机中运行此代码?世博会?网络?
你是否也传递你为了简洁而隐藏的帖子参数? 这可能是错误的根本原因。
答案 1 :(得分:1)
您能否尝试用以下代码替换您的代码:
const axios = require("axios");
async function Creq_testowy() {
const data = await axios.post(`http://192.168.0.4:8080/testowy`)
return data.data
}
module.exports = {
Creq_testowy,
}