我正在使用create-react-app和axios创建一个React应用程序,
并尝试从json服务器获取json响应数据。但这不起作用。
我正在使用react-scripts start
。
react应用程序和json-server都在同一docker容器上运行。 react应用使用3000端口,而json-server使用8888端口。
我可以使用curl -X GET localhost:8888/user
这样的curl命令从json服务器获取数据。
但是react应用无法连接到json服务器。
版本...
下面是我的代码和错误消息。
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
请告诉我解决此问题的方法...