Sunday, 2 April 2017

Express server serves my static files but does not handle requests to my API. What is happening?

I built a small app on top of a company's API. I created my own API to interact with their's. My app uses React-Create-App to scaffold, with Redux, and the server is Experss/Node.js. It works totally fine on localhost but when I deploy it on Heroku, it serves the bundle but doesn't hand any user http requests to the server. It returns a 404 not found. Heroku gives no errors in their logs.

My post install script runs the build, which bundles the app. I have set environment port variable in the heroku dashboard as well.

package.json

{
  "name": "event.me",
  "version": "0.1.0",
  "private": true,
    "engines":{
    "node": "7.2.1",
    "npm": "3.10.10"  
  },  
  "dependencies": {
    "axios": "^0.15.3",
    "body-parser": "^1.17.1",
    "express": "^4.15.2",
    "moment": "^2.18.1",
    "react": "^15.4.2",
    "react-dom": "^15.4.2",
    "react-progressbar.js": "^0.2.0",
    "react-redux": "^5.0.3",
    "react-router": "^3.0.0",
    "react-router-dom": "^4.0.0",
    "redux": "^3.6.0",
    "redux-logger": "^3.0.0",
    "redux-thunk": "^2.2.0"
  },
  "devDependencies": {
    "eslint": "^3.18.0",
    "eslint-config-airbnb": "^14.1.0",
    "eslint-plugin-jsx-a11y": "^4.0.0",
    "eslint-plugin-react": "^6.9.0",
    "eslint-plugin-import": "^2.2.0",
    "nodemon": "^1.11.0",
    "react-scripts": "0.9.5"
  },
  "scripts": {
    "start": "react-scripts start",
    "build": "react-scripts build",
    "test": "react-scripts test --env=jsdom",
    "eject": "react-scripts eject",
    "server": "node server/server.js",
    "postinstall": "npm run build"
  }
}

server.js file

const express = require('express');
const path = require('path');
const bodyParser = require('body-parser');
const routes = require('./routes');

const app = express();

app.use(express.static(path.resolve(__dirname, '..', 'build')));
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
app.use('/api', routes);
const port = process.env.PORT || 8080;

app.listen(port, () => console.log(`Listening on ${port}`));

routes.js

const routes = require('express').Router();
const users = require('./controllers/users.js');
const events = require('./controllers/events.js');

routes.post('/sigin', users.signin);
routes.post('/signup', users.signup);
routes.get('/events', events.getAll);
routes.post('/events', events.attendEvent);
routes.delete('/events', events.flakeEvent);
routes.patch('/events', events.updateEvent);
routes.delete('/singleevent', events.deleteEvent);
routes.post('/createevent', events.createEvent);

module.exports = routes;


via colbisaurusrex

No comments:

Post a Comment