【问题标题】:React + Express: Axios returns 405 Method Not Allowed on HerokuReact + Express:Axios 在 Heroku 上返回 405 Method Not Allowed
【发布时间】:2020-09-22 08:15:33
【问题描述】:

我正在开发一个带有 React 前端和 Express API 的应用程序,它们托管在同一台服务器上。

它在本地运行良好,但一旦我将它部署到 Heroku,从前端到后端的每个请求都会返回 405: Method Not Allowed。我一直在寻找答案,但大多数都指向using CORS,我已经这样做了。因此,我不知道我的问题是来自构建、滥用 axios 还是来自错误的 express.js 配置。

我也尝试过添加 react 代理 URL,但并没有解决问题。

目录结构如下:

├── Express
|   └── server.js
├── React
|   └── App.js
├── buildScript.js
└── package.json

这是我的 server.js 文件:

const express = require('express')
const bodyParser = require('body-parser')
const compression = require('compression')
const cors = require('cors')
const helmet = require('helmet')
const path = require('path');

// Import routes
const poisRouter = require('./routes/pois-route')
const autocompleteRouter = require('./routes/autocomplete-route')

// Set default port for express app
const PORT = process.env.PORT || 4001

const app = express()

app.use(cors())
app.use(helmet())
app.use(compression())
app.use(bodyParser.urlencoded({ extended: false }))
app.use(bodyParser.json())

// Serve static files from the React App
app.use(express.static(path.join(__dirname, 'build')));

// Implement Poi & Autocomplete routes
app.use('/pois', poisRouter)
app.use('/autocomplete', autocompleteRouter)

// Wildcard to send back to React
app.get('*', (req, res) => {
  res.sendFile(path.join(__dirname, 'build', 'index.html'));
});


// Start express app
app.listen(PORT, function() {
  console.log(`Server is running on: ${PORT}`)
})

来自 React 前端的示例请求,给我一个 405 错误:

  const fetchPoisFromAutocomplete = async () => {
    // Send GET request to 'autocomplete/fetch' endpoint

    axios
      .get('/autocomplete/fetch', {
        latitude: latitude,
        longitude: longitude
      })
      .then(response => {
        // Update the pois state
        console.dir(response.data)

      })
      .catch(error => console.error(`There was an error retrieving the poi list: ${error}`))
  }

fetchPoisFromAutocomplete();

Package.json 脚本:

  "scripts": {
    "build": "node ./buildScript",
    "build-front": "react-scripts build",
    "start": "node app/server.js",
    "start-server": "nodemon app/server.js",
    "start-front": "react-scripts start",
    "dev": "concurrently \"npm run start-server\" \"npm run start-front\" --kill-others --kill-others-on-fail",
    "test": "react-scripts test",
    "eject": "react-scripts eject",
    "heroku-postbuild": "react-scripts build"
  },

构建脚本:

const fs = require('fs')
const fse = require('fs-extra')
const childProcess = require('child_process')

if (fs.existsSync('./build')) {
  fse.removeSync('./build')
}

childProcess.execSync('react-scripts build', { stdio: 'inherit' })

fse.moveSync('./build', './server/build', { overwrite: true })

【问题讨论】:

    标签: reactjs express heroku axios


    【解决方案1】:

    尝试将端点的完整 url 放在 heroku 上:

    .get('/autocomplete/fetch', {
    

    .get('https://your-heroku-app.herokuapp.com/autocomplete/fetch'
    
    

    看看这是否有效。我怀疑您的反应应用程序实际上是在尝试调用与托管 API 的位置不同的 URL。

    【讨论】:

    • 我之前尝试过,但没有运气。我认为这个问题与我的构建有关。
    【解决方案2】:

    在堆栈溢出中,有人遇到了这个问题,请参见下面的其中一个 cmets,不确定是否是同一个问题。

    应用程序在 heroku 服务器上。我已联系支持人员,他们回复:“create-react->app-buildpack 使用 heroku/static buildpack,而后者又使用 nginx Web 服务器。>不幸的是,nginx 不允许来自静态页面的 POST 调用。您需要进行一个 >GET 请求在这里。”

    I am getting 405 method not allowed

    不确定是否是您的情况,但请确保您没有将 Build 文件夹上传到您的存储库,因为一旦您将其上传到 heroku,这将破坏它。

    【讨论】:

    • 嗨,约翰,欢迎来到 Stack Overflow!如果您认为其他人已经回答了该问题,最好将问题标记为重复问题并让版主过滤掉重复的问题。
    • 我不确定这是不是同样的情况,因为我能够毫无问题地进行 POST,我的问题是将 Build 文件夹部署到我的 repo 并将其上传到 Heroku,一旦我移动它,我的应用程序有效。只是分享,因为我不确定 Marwann 是否有同样的问题。
    猜你喜欢
    • 1970-01-01
    • 2011-09-25
    • 1970-01-01
    • 2021-06-14
    • 2016-12-04
    • 1970-01-01
    • 2014-09-03
    • 2014-04-09
    • 2015-07-01
    相关资源
    最近更新 更多