【发布时间】:2019-03-02 19:45:06
【问题描述】:
鉴于以下设置:
server.js
const express = require('express')
const path = require('path')
const app = express()
const cors = require('cors')
const port = process.env.PORT || 8080
app.use(cors())
app.get('/api', (req, res) => {
res.send({code: 200, message: 'I have arrived!'})
})
app.listen(port, () => console.log(`I can hear your thoughts on ${port}`))
以及带有调用的展示组件:
App.js
componentDidMount() {
fetch(`/api`, {
method: 'GET',
headers: {
'Content-Type': 'application/json',
'Accept': 'application/json'
}
}).then(res => {
console.log(res)
return res.json()
}).then(response => {
console.log(response)
this.data = response
}).catch(error => {
this.error = error.message || error.error
})
}
package.json:
"scripts": {
"start": "npm-run-all --parallel start:client start:server",
"start:client": "node node_modules/react-native/local-cli/cli.js start",
"start:server": "node server.js",
"test": "jest"
},
我正在通过yarn start 运行该应用程序,并且我看到了日志:“我能听到你的想法”... 但是,从未发出 fetch 调用。如果我在 fetch 调用中提供另一个完全限定的 url,它会按预期返回数据,但是我无法从组件中访问 express api。
- 如果我将
http://localhost:8080/api放在浏览器中,我会得到响应。 - 如果我将
http://localhost:8080/api放在 fetch 调用中,它将永远不会被调用(或者至少看起来不会)。
如何正确配置它以在本地运行时调用 express api?
一如既往地感谢任何和所有方向,所以提前感谢!
【问题讨论】:
-
您的问题是由在您的 api 调用中使用术语
localhost引起的。您需要使用计算机的 IP 地址。192.168.###.###/api/之类的东西或者你的 IP 地址是什么 -
不幸的是,用提取 URL 中的 IP 替换具有相同的结果。
-
你的组件确定被挂载了吗?如果是这样,您是否从获取请求中收到任何错误?您是否尝试在服务器上添加额外的日志以查看请求是否到达?您是否尝试过不同的 api 端点,例如
'https://jsonplaceholder.typicode.com/todos/1'? -
它不在上面的代码中,但我正在记录 componentDidMount,所以是的,它正在安装。目前根本没有网络日志。如前所述:
...If I supply another fully qualified url within the fetch call it returns the data as expected- 所以是的,我也尝试过。{userId: 1, id: 1, title: "delectus aut autem", completed: false}通过提供的 url 记录。调试服务器是否有问题并尝试运行快速服务器? -
react-native或expo?
标签: node.js api express react-native