首页 > 解决方案 > 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。

版本...

以下是我的代码和错误消息。

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

请告诉我解决此问题的解决方案...

标签: javascriptnode.jsjsonreactjs

解决方案


推荐阅读