【发布时间】: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