【问题标题】:ReactJS app with nodejs/express for backend - can't get api to backend working带有 nodejs/express 后端的 ReactJS 应用程序 - 无法让 api 到后端工作
【发布时间】:2019-12-16 06:51:12
【问题描述】:

我正在尝试实现一个需要访问数据库的 React 应用程序。据我所知,这可以使用 nodejs/express 作为后端来完成。此外,我的印象是,通过在我的 react package.json 文件中添加一个代理条目,我可以将 fetch 调用的“/api”请求重定向到后端服务器。但是,我认为它不起作用。在浏览器控制台中,在 localhost:3000(这是 NPM 反应服务器)上显示 404 错误。我的后端在 5000 端口上运行。

我可以访问后端服务器的“http://localhost:5000/api”,它按设计返回 JSON。

这是我的 react package.json 文件:

{
  "name": "ubwo",
  "version": "0.1.0",
  "private": true,
  "proxy":"http://localhost:5000/api",
  "dependencies": {
    "react": "^16.8.6",
    "react-dom": "^16.8.6",
    "react-redux": "^7.1.0",
    "react-router": "^5.0.1",
    "react-router-dom": "^5.0.1",
    "react-scripts": "3.0.1",
    "redux": "^4.0.1",
    "redux-thunk": "^2.3.0"
  },
  "scripts": {
    "start": "react-scripts start",
    "build": "react-scripts build",
    "test": "react-scripts test",
    "eject": "react-scripts eject"
  },
  "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"
    ]
  },
  "resolutions": {
    "browserslist": "4.6.2",
    "caniuse-lite": "1.0.30000974"
  }
}

这是我的“测试”React 代码。我对 fetch 不太熟悉,所以代码可能需要一些更改?:

componentDidMount() {
    this.callApi()
        .then(res => this.setState({ response: res.express}))
        .catch(err => console.log(err));
}

callApi = async() => {
    const response = await fetch('/api/cust/all',{
        headers:{
            "accepts":"application/json"
        }
    });
    const customers = await response.json();
    if (response.status !== 200) throw Error(customers.message);

    return customers;
}

【问题讨论】:

  • 你可以试试"proxy":"http://localhost:5000"吗?我不太确定,但使用当前设置代理可能会为您的端点重定向到类似 /api/api/cust/all 的内容。
  • 如果您尝试npm run build 并从那里开始工作,它是否有效? AFAIK react-scripts 使用 webpack-dev-server 所以你的代理最好通过 devServer.proxy 在你的 webpack 配置中设置(在你弹出 iirc 之前它是隐藏的)作为一个简单的修复,你可以删除代理并进行获取请求fetch('localhost:5000/api/cust/all') - 虽然一旦你把它托管在某个地方,基本 url 将从 localhost 改变。
  • 代理可以正常工作,并且可以使用 CRA 进行任何自定义配置,因此可以在开发中使用“react-scripts”。无需弹出或进行任何自定义设置。如果 OP 尝试直接发出请求,他们可能会遇到 CORS 问题。
  • devserkan:如果我不能像之前的一些回复所指出的那样使用直接 URL,您知道解决方案吗?我不是想重新发明轮子。我正在使用代理,因为我在几个不同的博客上阅读了关于该主题的解决方案。如果有更好的方法,无论是开发还是生产,我都愿意接受。

标签: node.js reactjs express


【解决方案1】:

您还可以检查您的主服务器文件的后端是否使用了 json 解析器,例如:

express.urlencoded([options])

const bodyParser = require('body-parser);
bodyParser.json([options])

【讨论】:

    【解决方案2】:

    当您在 fetch 调用中使用 /api/foo 时,它将针对您当前所在的 url 执行请求。所以您的 API 请求正在扩展到

    http://localhost:3000/api/foo

    正如您所说,您的 API 服务器在 http://localhost:5000 上运行。所以你需要在这里做的是提供你的fetch请求的完整路径。

    fetch(`http://localhost:5000/api/foo`)
    

    你可能猜到了,这会在你投入生产的时候出现问题,所以一个典型的模式是使用一个可以配置的环境变量:

    fetch(`${process.env.API_URL}/api/foo`)
    

    create-react-app environment variable docs

    【讨论】:

      【解决方案3】:

      您可能应该删除 package.json 文件中代理值末尾的 /api

      希望对你有帮助

      【讨论】:

      • 我最初没有/api,但我在尝试不同配置的过程中添加了它以尝试使其正常工作。 :)
      猜你喜欢
      • 2020-08-27
      • 1970-01-01
      • 1970-01-01
      • 2019-09-16
      • 1970-01-01
      • 2020-06-05
      • 2021-11-07
      • 2021-12-22
      相关资源
      最近更新 更多