I'm trying to launch an API on Heroku for the first time. I've tried many a solution but everything I do seems to create more problems than solve them. I'm not sure what to try next. I know Heroku dynamically generates the port, which it is doing as I've tested this. My mongoDB ref is being used as I used to get the "URI() must be a string"
error but that has been resolved. heroku local web
works fine as well. I've tried heroku restart
to no avail.
I've seen people mention
const path = require('path');
if (process.env.NODE_ENV === 'production') {
//set static folder
server.use(express.static('client/build'));
}
server.get('*', (req, res) => {
res.sendFile(path.resolve(__dirname, 'client', 'build', 'index.html'));
});
but I'm not well versed in understanding how to use a build folder and it didn't solve my problem.
I'm getting the SyntaxError: Unexpected end of input
error in the log. Everything builds and I get a status of "up" until I go to the page and it spits out a get request that goes unanswered.
Here's my code:
const express = require('express');
const mongoose = require('mongoose');
const toDoRoutes = require('./routes');
//creates server and sets use cases to handle JSON and todo routes
const server = express();
server.use(express.json());
//sets headers to allow apps to interact with eachother
server.use((req, res, next) => {
res.setHeader('Access-Control-Allow-Origin', '*');
res.setHeader(
'Access-Control-Allow-Headers',
'Origin, X-Requested-With, Content-Type, Accept, Authorization'
);
res.setHeader('Access-Control-Allow-Methods', 'GET, POST, PATCH, DELETE');
next();
});
server.use('/api/todos', toDoRoutes);
//connects mongodb server to API and then starts server on success
mongoose
.connect(`${process.env.DB}`)
.then(() => {
server.listen(process.env.PORT || 3001);
})
.catch((error) => console.log(error.message, db));
CodePudding user response:
Ashamed to say I figured out the issue and it was a simple one. I scourged the internet only to finally see a post that reminded me my API wasn't going to have a '.../' route, but a '.../api/todos' route. Once I entered the correct URL it, of course, worked.
Posting this answer to hopefully help the next lost soul try this out before trying a bunch of stuff that won't work like I did.