FIX:在遵循一些建议后,我放弃了setupProxy,并将完整的API URL放入axios请求中。这引发了一个cors错误,所以我导入了cors&将CCD_ 1添加到我的index.js&当我重新部署应用程序时,它按预期运行
我第一次尝试部署一个MERN堆栈练习项目。我是一个全新的程序员。
我的项目在开发/本地运行得非常好。我在localhost:3000上运行的React应用程序连接到我部署到Heroku&可以成功提出请求。然而,当我打开部署的Netlify应用程序时,它无法加载任何数据&Heroku日志没有显示任何活动,这表明它根本没有连接到后端。
以下是一些可能相关的代码:
---------------后端---------------
environment.js(信息经过<>编辑(
export const dbURI = process.env.MONGODB_URI || 'mongodb+srv://<name>:<password>@festivalist.iyq41.mongodb.net/festivalist?retryWrites=true&w=majority'
export const port = process.env.PORT || 4000
export const secret = process.env.SECRET || '<secret>'
index.js
import express from 'express'
const app = express()
import mongoose from 'mongoose'
import router from './config/router.js'
import { port, dbURI } from './config/environment.js'
const startServer = async () => {
try {
await mongoose.connect(dbURI, { useNewUrlParser: true, useCreateIndex: true, useUnifiedTopology: true })
console.log('🚀 Database has connected successfully')
app.use(express.json())
app.use((req, _res, next) => {
console.log(`🚨 Incoming request: ${req.method} - ${req.url}`)
next()
})
app.use('/api', router)
app.listen(port, () => console.log(`🚀 Express is up and running on port ${port}`))
} catch (err) {
console.log('🆘 Something went wrong starting the app')
console.log(err)
}
}
startServer()
package.json
{
"name": "sei-project-three",
"version": "1.0.0",
"main": "index.js",
"dependencies": {
"bcrypt": "^5.0.1",
"dotenv": "^10.0.0",
"express": "^4.17.1",
"jsonwebtoken": "^8.5.1",
"mongo": "^0.1.0",
"mongoose": "^5.12.0",
"nodemon": "^2.0.14"
},
"type": "module",
"scripts": {
"test": "echo "Error: no test specified" && exit 1",
"seed": "node db/seeds.js",
"dev": "nodemon",
"start": "node index.js"
},
"devDependencies": {
"eslint": "^7.22.0"
},
"engines": {
"node": "16.8.0"
}
}
---------------前端---------------
setupProxy.js
const { createProxyMiddleware } = require('http-proxy-middleware')
module.exports = function (app) {
app.use(createProxyMiddleware('/api', { target: 'https://festivalist-api.herokuapp.com', "changeOrigin": true }))
}
示例请求
const ArtistIndex = () => {
const [artists, setArtists] = useState([])
useEffect(() => {
const getData = async () => {
const { data } = await axios.get('/api/artists')
setArtists(data)
}
console.log('artists2', artists)
getData()
}, [])
package.json
{
"name": "client",
"version": "0.1.0",
"private": true,
"dependencies": {
"axios": "^0.21.1",
"http-proxy-middleware": "^1.0.5",
"mapbox-gl": "^2.2.0",
"react": "^17.0.2",
"react-dom": "^17.0.2",
"react-map-gl": "^5.2.5",
"react-mapbox-gl": "^5.1.1",
"react-router-dom": "^5.2.0",
"react-scripts": "4.0.3",
"sass": "^1.42.1",
"semantic-ui-css": "^2.4.1",
"semantic-ui-react": "^2.0.3"
},
"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"
]
},
"devDependencies": {
"@typescript-eslint/eslint-plugin": "^4.25.0",
"@typescript-eslint/parser": "^4.25.0",
"babel-eslint": "^10.1.0",
"eslint": "^7.27.0",
"eslint-config-react-app": "^6.0.0",
"eslint-plugin-flowtype": "^5.7.2",
"eslint-plugin-import": "^2.23.3",
"eslint-plugin-jsx-a11y": "^6.4.1",
"eslint-plugin-react": "^7.23.2",
"eslint-plugin-react-hooks": "^4.2.0"
}
}
一些注意事项:
- 我已将MongoDB Atlas 0.0.0.0/0中的所有IP地址列入白名单
- 我不确定为什么,但我必须在herokuapiurl的末尾放上"/api/"才能获得数据,即:
https://festivalist-api.herokuapp.com/api/festivals
- 我在Heroku中添加了Config Vars,但我认为这阻止了我的应用程序在本地工作,所以我删除了它们。我也不完全明白他们在做什么
我已经尝试部署它好几天了,所以任何建议都将是帮助或任何故障排除提示,因为我是编码新手!感谢
您必须在heroku api的末尾放入'/api',因为这是您在后端index.jsapp.use('/api', router)
中使用的内容
这个问题似乎与中端setupProxy.js有关,因为您已经可以ping API了。一种解决方法是只更新您的请求以使用完整的URI。即
const ArtistIndex = () => {
const [artists, setArtists] = useState([])
useEffect(() => {
const getData = async () => {
const { data } = await axios.get('https://festivalist-api.herokuapp.com/api/artists')
setArtists(data)
}
console.log('artists2', artists)
getData()
}, [])