![](/img/trans.png)
[英]How can I solve this 422 error when trying to send information to the database using an axios POST request?
[英]Why i'm getting a network error, when trying to send a post request using axios
嘗試使用 axios 發送發布請求時出現網絡錯誤。
錯誤:node_modules\axios\lib\core\createError.js 處的網絡錯誤:node_modules\axios\lib\adapters\xhr.js 中的 createError 中的 15:17:node_modules\event-target-shim\dist 處的 handleError 中的 81:22 \event-target-shim.js:818:20 在 EventTarget.prototype.dispatchEvent 在 node_modules\react-native\Libraries\Network\XMLHttpRequest.js:600:10 在 setReadyState 在 node_modules\react-native\Libraries\Network\XMLHttpRequest .js:395:6 in __didCompleteResponse 在 node_modules\react-native\Libraries\vendor\emitter\EventEmitter.js:189:10 在發出在 node_modules\react-native\Libraries\BatchedBridge\MessageQueue.js:416:4 在 __callFunction在 node_modules\react-native\Libraries\BatchedBridge\MessageQueue.js:109:6 in __guard$argument_0 at node_modules\react-native\Libraries\BatchedBridge\MessageQueue.js:364:10 in __guard at node_modules\react-native\Libraries \BatchedBridge\MessageQueue.js:108:4 in 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() 時,一切正常,但是在我嘗試導入 function 后,它應該做完全相同的事情,我得到了這個網絡錯誤。
上面提到的帶有 function 的庫:
const {Creq_testowy} = require("./Creq_testowy");
module.exports={
testowy: Creq_testowy,
}
Function 本身:
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() 時一切正常? 為什么在使用導入的 function 時出現此錯誤?
當 axios 已經返回一個時,為什么還要創建一個 promise? 你能試試這個嗎?
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);
}
}
您是否在本機運行此代碼? expo? web?
您是否還傳遞了為簡潔起見隱藏的帖子參數? 這可能是該錯誤的根本原因。
您可以嘗試用以下代碼替換您的代碼:
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,
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.