javascript - ReactJS 得到 net::ERR_CONNECTION_REFUSED 错误
问题描述
我正在使用 create-react-app 和 axios 创建一个反应应用程序,并尝试从 json-server 获取 json 响应数据。但它不起作用。我正在使用react-scripts start
.
react app 和 json-server 都在同一个 docker 容器上运行。react 应用程序使用 3000 端口,json-server 使用 8888 端口。
我可以使用这样的 curl 命令从 json-server 获取数据curl -X GET localhost:8888/user
。但是反应应用程序无法连接到 json-server。
版本...
- 反应:16.13.1
- 反应脚本:3.4.1
- axios:0.19.2
- json服务器:0.16.1
- 码头工人:19.03.8
以下是我的代码和错误消息。
ReactJS 代码
import axios from 'axios'
const client = axios.create({
baseURL: 'http://localhost:8888',
timeout: 1000,
})
const getAll = async () => {
try {
const res = await client.get('/user')
const users = res.data.users
return users
} catch (error) {
console.log(error)
}
}
json服务器代码
const jsonServer = require('json-server')
const server = jsonServer.create()
const router = jsonServer.router('./src/mock/db.json')
router.render = (req, res) => {
res.header('Access-Control-Allow-Origin', '*')
if (req.url.match(/user/)) {
if (req.route.path === '/:id') {
res.jsonp({
message: 'mock server...',
user: res.locals.data,
})
} else {
res.jsonp({
message: 'mock server...',
users: res.locals.data,
})
}
}
}
server.use(router)
server.listen(8888, 'localhost', () => {
console.log('JSON server is running...')
})
错误信息
xhr.js:178 GET http://localhost:8888/user net::ERR_CONNECTION_REFUSED
dispatchXhrRequest @ xhr.js:178
xhrAdapter @ xhr.js:12
dispatchRequest @ dispatchRequest.js:52
Promise.then (async)
request @ Axios.js:61
Axios.<computed> @ Axios.js:76
wrap @ bind.js:9
getAll @ user.js:5
(anonymous) @ PersonalCards.js:9
commitHookEffectListMount @ react-dom.development.js:19731
commitPassiveHookEffects @ react-dom.development.js:19769
callCallback @ react-dom.development.js:188
invokeGuardedCallbackDev @ react-dom.development.js:237
invokeGuardedCallback @ react-dom.development.js:292
flushPassiveEffectsImpl @ react-dom.development.js:22853
unstable_runWithPriority @ scheduler.development.js:653
runWithPriority$1 @ react-dom.development.js:11039
flushPassiveEffects @ react-dom.development.js:22820
(anonymous) @ react-dom.development.js:22699
workLoop @ scheduler.development.js:597
flushWork @ scheduler.development.js:552
performWorkUntilDeadline @ scheduler.development.js:164
请告诉我解决此问题的解决方案...
解决方案
推荐阅读
- javascript - 造句只能包含数组内的字符
- c# - C# HTTPListener 服务器无法从 LAN 中的其他设备访问
- json - 从 json 的嵌套对象中获取值而不创建额外的类
- python - 如何使用 HDF5 存储和加载 Python 字典
- google-bigquery - IF Conditional to Run Schedule Query
- json - 在颤振中,我将如何从生成的文本框中保存文本框输入?
- connection-string - Power BI Report Builder 表格模型连接查询大小限制问题
- html - 更漂亮:保持空行分隔 HTML/JSX HTML 中的属性
- r - 我正在尝试制作一个频率表,其中 Var1 仅使用一个值,而 Var3 未出现在表中但过滤表中的数据
- c# - Serilog TcpSink 不抛出异常