首页 > 解决方案 > 部署到 Heroku 时如何在没有 create-react-app 的情况下在 React 应用程序中设置代理

问题描述

我基于我的模板(https://github.com/MikeMikhailov/React-Template)创建了一个 React 应用程序。现在我正在尝试将它部署到 Heroku,并连接到 Express REST Api。我想知道,如何设置代理,以便为 /api/* 的所有请求提供我后端的来源。我已经尝试过设置一个 static.json 文件

"proxies": {
  "/api" : {
    "origin": "https://${BACKEND_URL}/api"
  }
}

但它似乎没有用,因为我不断收到 405,因为对前端的 /api 提出了请求。

index_bundle.js?bace5e170912d902f943:12 POST https://${FRONTEND_URL}/api/auth/signup 405 (Method Not Allowed)

在不使用 create-react-app 的情况下还有其他方法吗?

静态.json

{
  "root": "dist/",
  "routes": {
    "/**":"index.html"
  },
  "proxies": {
    "/api": {
      "origin": "https://${BACKEND_URL}/api"
    }
  }
}

包.json

{
  "name": "warbler-client",
  "version": "1.0.0",
  "main": "./src/index.jsx",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "dev": "node_modules/.bin/webpack-dev-server --mode development --hot",
    "build": "node_modules/.bin/webpack --config webpack.prod.js --mode production",
    "start": "node_modules/.bin/http-server ./dist"
  },
  "license": "MIT",
  "dependencies": {
    "http-server": "^0.12.1",
    "jwt-decode": "^2.2.0",
    "ky": "^0.19.0",
    "moment": "^2.24.0",
    "normalize.css": "^8.0.1",
    "prop-types": "^15.7.2",
    "react": "^16.13.0",
    "react-dom": "^16.13.0",
    "react-moment": "^0.9.7",
    "react-redux": "^7.2.0",
    "react-router-dom": "^5.1.2",
    "react-router-prop-types": "^1.0.4",
    "redux": "^4.0.5",
    "redux-thunk": "^2.3.0",
    "semantic-ui-css": "^2.4.1",
    "semantic-ui-react": "^0.88.2"
  },
  "devDependencies": {
    "@babel/core": "^7.8.7",
    "@babel/plugin-proposal-class-properties": "^7.8.3",
    "@babel/plugin-transform-runtime": "^7.8.3",
    "@babel/preset-env": "^7.8.7",
    "@babel/preset-react": "^7.8.3",
    "@babel/runtime": "^7.8.7",
    "babel-eslint": "^10.1.0",
    "babel-loader": "^8.0.6",
    "css-loader": "^3.4.2",
    "eslint": "^6.8.0",
    "eslint-config-airbnb": "^18.0.1",
    "eslint-config-prettier": "^6.10.0",
    "eslint-plugin-import": "^2.20.1",
    "eslint-plugin-jsx-a11y": "^6.2.3",
    "eslint-plugin-react": "^7.19.0",
    "eslint-plugin-react-hooks": "1.7.0",
    "favicons-webpack-plugin": "^3.0.1",
    "file-loader": "^5.1.0",
    "html-webpack-plugin": "^4.0.0-beta.11",
    "js-beautify": "^1.10.3",
    "mini-css-extract-plugin": "^0.9.0",
    "node-sass": "^4.13.1",
    "prettier": "^1.19.1",
    "sass-loader": "^8.0.2",
    "webpack": "^4.42.0",
    "webpack-cli": "^3.3.11",
    "webpack-dev-server": "^3.10.3"
  },
}

标签: reactjsherokuproxy

解决方案


弄清楚了。

问题是默认情况下,Heroku 检测到 Node.js 应用程序,成功构建它,并通过我的启动脚本提供它。所以它没有使用static.json。要解决这个问题,只需在 Heroku 上的 Node.js 之后添加一个静态网站构建包。我希望这对某人有帮助!


推荐阅读