【问题标题】:unable to use json-server and react together无法使用 json-server 并一起做出反应
【发布时间】:2020-07-14 15:32:03
【问题描述】:

我正在尝试在我已经通过 React 设置的项目目录中使用 json-server:npx create-react-app new-app。在新应用中 目录,我有一个文件db.json 有一些内容:

{
  "notes": [
    {
      "id": 1,
      "content": "first content",
    },
    {
      "id": 2,
      "content": "content 2",
    }
  ]
}

我还安装了带有npm install json-server --save-dev 的json-server。然后,我通过:npx json-server --port 3001 --watch db.json 在端口 3001 上运行服务器,到目前为止一切运行顺利,我可以在http://localhost:3001/notes 上看到注释文件。

此时,到packages.json,在“脚本”下,我添加了这样的服务器配置:

{
  "name": "new-app",
  "version": "0.1.0",
  "private": true,
  "dependencies": {
    "@testing-library/jest-dom": "^4.2.4",
    "@testing-library/react": "^9.5.0",
    "@testing-library/user-event": "^7.2.1",
    "react": "^16.13.1",
    "react-dom": "^16.13.1",
    "react-scripts": "3.4.1"
  },
  "scripts": {
    "start": "react-scripts start",
    "build": "react-scripts build",
    "test": "react-scripts test",
    "eject": "react-scripts eject",
    "server": "json-server -p3001 --watch db.json" // ADDED THIS
  },
  "eslintConfig": {
    "extends": "react-app"
  },
  "browserslist": {
    "production": [
      ">0.2%",
      "not dead",
      "not op_mini all"
    ],
    "development": [
      "last 1 chrome version",
      "last 1 firefox version",
      "last 1 safari version"
    ]
  },
  "devDependencies": {
    "json-server": "^0.16.1"
  }
}

根据我所关注的参考资料,这应该显示来自http://localhost:3001 的所有反应内容,但我得到的只是一个标题为 React App 的空白页面(也没有图标)。我的根目录如下(除了提到的没有变化):

https://imgur.com/a/MR0NYrr

谁能指出这里出了什么问题?或者,他们如何设法正确设置 react 和 json-server?

以这种方式设置时,src 文件夹中的 index.js 文件(和其他 .js 文件)似乎没有被 public 文件夹中的 index.html 使用。

【问题讨论】:

  • 您好!您是否从浏览器的控制台获得任何类型的输出?
  • 不,我在浏览器中的控制台是空的。我尝试使用 "console.log("hi")" 进行测试,但控制台中没有显示任何内容

标签: javascript reactjs json-server


【解决方案1】:

您想查看网站而不是 json-server 的内容,我说得对吗?也许试试http://localhost:3000

【讨论】:

  • 实际上,我可能已经让它工作了。我打开了另一个终端来运行 npm start(所以 2 个服务器,在 3000 和 3001),我能够看到 React 的东西并访问 @ 987654322@。我没有意识到我必须同时拥有 3000(通过 npm start)和 3001(通过 npm run)。谢谢
猜你喜欢
  • 2018-04-28
  • 2018-03-28
  • 1970-01-01
  • 1970-01-01
  • 2021-05-17
  • 2017-08-02
  • 1970-01-01
  • 2020-10-26
相关资源
最近更新 更多