【发布时间】:2021-01-18 16:11:44
【问题描述】:
我在 react-native 中有一个前端,它使用 axios 库进行 API 调用;如下图所示:
function addItem(item) {
if (!item) {
Alert.alert('Error', 'Please enter a valid item.', [{text: 'Ok'}]);
} else {
axios.get('/additem', {
Id: items[items.length - 1].id + 1,
Text: item
})
.then((res) => {
setItems([...items, {id: res.id, text: res.text}])
})
.catch((err) => {
console.log(err);
})
}
}
如您所见,我正在向端点发出 GET 请求,并使用响应数据。
这是我的后端端点在 Node.js 中的样子(使用 Express.js):
app.get('/additem', (req, res) => {
const item = new Item({
id: req.body.Id,
text: req.body.Text
});
item.save()
.then((result) => {
res.send(result)
})
.catch((err) => {
console.log(err)
})
})
save() 函数和 Item 对象只是 MongoDB 特有的,所以不要太担心。
我正在使用proxy 来“连接”后端和前端,这意味着我已将其添加到我前端的package.json 文件中:
{
"name": "firstProj",
"version": "0.0.1",
"private": true,
"proxy": "https://localhost:5000",
"scripts": {
"android": "react-native run-android",
"ios": "react-native run-ios",
"start": "react-native start",
"test": "jest",
"lint": "eslint ."
},
localhost:5000 是我的 node.js 后端运行的地方
现在,当我尝试通过前端访问端点时,react-native 对我大喊:
LOG [Error: Network Error]
零线索为什么会发生这种情况。任何帮助表示赞赏。 :) 如果您需要更多信息,请告诉我。
非常感谢。
编辑: 这是我的代码未捕获时的完整错误:
Possible Unhandled Promise Rejection (id: 0):
Error: Network Error
createError@http://10.0.2.2:8081/index.bundle?platform=android&dev=true&minify=false:99656:26
handleError@http://10.0.2.2:8081/index.bundle?platform=android&dev=true&minify=false:99560:27
dispatchEvent@http://10.0.2.2:8081/index.bundle?platform=android&dev=true&minify=false:32348:31
setReadyState@http://10.0.2.2:8081/index.bundle?platform=android&dev=true&minify=false:31432:33
__didCompleteResponse@http://10.0.2.2:8081/index.bundle?platform=android&dev=true&minify=false:31248:29
emit@http://10.0.2.2:8081/index.bundle?platform=android&dev=true&minify=false:3537:42
__callFunction@http://10.0.2.2:8081/index.bundle?platform=android&dev=true&minify=false:2765:36
http://10.0.2.2:8081/index.bundle?platform=android&dev=true&minify=false:2497:31
__guard@http://10.0.2.2:8081/index.bundle?platform=android&dev=true&minify=false:2719:15
callFunctionReturnFlushedQueue@http://10.0.2.2:8081/index.bundle?platform=android&dev=true&minify=false:2496:21
callFunctionReturnFlushedQueue@[native code]
【问题讨论】:
-
能否提供快递服务器中的错误日志
-
或者您可以尝试将请求更改为
axios.get('/additem', { params:{ Id: items[items.length - 1].id + 1, Text: item } }) -
@Musthafa 我在帖子中添加了完整的错误列表,我尝试添加“参数”仍然没有运气:(
-
好吧,也许是因为我们需要以字符串格式发送参数。将参数更改为
params:JSON.stringify({Id:[items.length - 1].id+1, Text:item}) -
只是一个问题,但是您是在为 axios 定义根 URL 吗?
axios.get('/addItem')正在查询您的 UI 应用程序而不是您的 API。如果您使用完整的 url 到您的后端会发生什么?试试axios.get('http://localhost:5000/addItem')
标签: node.js react-native express axios http-get