Reputation: 11
I am building a simple mern app that works fine on my local environment, but when deploying to Heroku, it serves the react app fine but 404s on the API calls. I can't seems to figure out the issue. I'm sending requests using Axios. I checked the network requests and they all look good, but still come back 404.
i have tried changing the scripts inside my package.json and still no luck.
Here's the server code... Any idea why this is failing?
const express = require('express');
const mongoose = require('mongoose');
const fileUpload = require('express-fileupload')
const cors = require('cors')
const app = express();
const routes = require('./routes');
const PORT = process.env.PORT || 3001;
// Setup middlewares
app.use(express.urlencoded({ extended: true }));
app.use(express.json());
app.use(fileUpload())
app.use(cors())
// app.use(methodOverride('_method'))
if (process.env.NODE_ENV === 'production') {
app.use(express.static('client/build'));
}
app.use("/",routes);
require('./services/passport');
// Connect database
// mongoose.connect(process.env.MONGODB_URI || 'mongodb://localhost/userstockitem', { useNewUrlParser: true, useCreateIndex: true, useUnifiedTopology: true, useFindAndModify: false });
mongoose.connect(MONGODB_URI || 'mongodb://localhost/profile', { useNewUrlParser: true, useCreateIndex: true, useUnifiedTopology: true, useFindAndModify: false });
mongoose.connection.on('connected', ()=>{
console.log('mongoose is connected')
})
app.listen(PORT,()=>{
console.log(`listening on PORT ${PORT}`)
});
`
and here's my package.json
{
"name": "blogster",
"version": "1.0.0",
"description": "",
"main": "index.js",
"engines": {
"node": "12.16.1",
"npm": "6.13.4"
},
"scripts": {
"start": "if-env NODE_ENV=production && npm run start:prod || npm run start:dev",
"start:prod": "node index.js",
"start:dev": "concurrently \"nodemon --ignore 'client/*'\" \"npm run client\"",
"client": "cd client && npm run start",
"install": "cd client && npm install",
"build": "cd client && npm run build",
"heroku-postbuild": "npm run build"
},
"keywords": [],
"author": "",
"license": "ISC",
"devDependencies": {
"concurrently": "^5.0.0"
},
"dependencies": {
"axios": "^0.19.0",
"bcryptjs": "^2.4.3",
"body-parser": "^1.19.0",
"chart.js": "^2.9.4",
"cors": "^2.8.5",
"ejs": "^3.1.5",
"express": "^4.17.1",
"express-fileupload": "^1.2.0",
"gridfs-stream": "^1.1.1",
"if-env": "^1.0.4",
"jwt-simple": "^0.5.6",
"method-override": "^3.0.0",
"mongoose": "^5.9.18",
"multer": "^1.4.2",
"multer-gridfs-storage": "^4.2.0",
"mysql": "^2.17.1",
"passport": "^0.4.1",
"passport-jwt": "^4.0.0",
"passport-local": "^1.0.0",
"plotly.js": "^1.54.2",
"react": "^17.0.1",
"react-chartjs-2": "^2.11.1",
"react-helmet": "^6.1.0",
"react-images-upload": "^1.2.8",
"react-live-clock": "^5.0.13",
"react-plotly.js": "^2.4.0",
"react-sound": "^1.2.0",
"validator": "^13.1.1"
}
}
My react routes in case that would be an issue
const multer = require('multer')
const upload = multer({dest:''})
router.route('/myimages')
.get(requireAuth,getMyImages)
.post(requireAuth,upload.single('file'),postMyImages)
my controller :
postMyImages: async (req, res) => {
const { fileName,filePath } = req.body;
console.log(req.body,'console.log filename and filepath')
if(req.files === null) {
return res.status(400).json({msf:'no file uploaded'})
}
try {
const file = req.files.file
file.mv(`${__dirname}/../client/public/images/${file.name}`,async (err)=>{
if(err){
console.error(err)
return res.status(500).send(err)
}
const newImage = await new Image({fileName:file.name,filePath:`/images/${file.name}`, user: req.user._id}).save();
req.user.myImages.push(newImage);
console.log(newImage,'new image')
await req.user.save();
return res.status(200).json(newImage);
})}catch (e) {
console.log('error not hitting ')
return res.status(403).json({ e });
}
},
getMyImages: async (req, res) => {
try {
const images = await Image.find({ user: req.user._id });
return res.json(images);
} catch (e) {
return res.status(403).json({ e });
}
}
my axios call
componentDidMount = () => {
this.getMyImage()
console.log('getting images....')
}
getMyImage = () => {
axios.get('/api/user/myimages',{headers: { 'authorization': localStorage.getItem('token')}})
.then((response)=>{
this.setState({myImages:response.data.reverse()})
console.log("myImages:response.data ", response.data)
})
}
handleRequest = (event) => {
event.preventDefault()
const data = new FormData();
const {file} = this.state
data.append('file', file)
axios.post('/api/user/myimages',data,{ 'Content-Type':'multipart/form-data',headers: { 'authorization': localStorage.getItem('token')}})
.then((response)=>{
const {fileName,filePath} = response.data
console.log(response.data,'response.data filename and filepath')
this.setState({uploadedFile:response.data})
this.getMyImage()
})
}
Upvotes: 0
Views: 88