how to deploy app to heroku and proxy API request

Viewed 301

Can you help me find what's wrong when I try to deploy my fullstack app to heroku. where can I find the solution to make my http requests work ?

I have tried :

  • adding a proxy in the package.json
  • using npm http-proxy-middleware

Nothing seems to work ??

This is my index.js

const express = require("express");
const bodyParser = require("body-parser");
require('dotenv').config();
const app = express();
const { createProxyMiddleware } = require("http-proxy-middleware");

const path = require("path");
const routes = express.Router()
const {  getAll, getSingle, postArticle, postComment, postVote } = require("./routes");

const cors = require("cors");
app.use(cors());
app.use('/articles', routes);
routes.use("/",  getAll);
routes.use("/:id", getSingle)
routes.use("/:id/upvote", postVote);
routes.use("/insert", postArticle);
// create another collection comment
routes.use("/:id/add-comment", postComment);

//middleware
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());


// Step 1:
app.use(express.static(path.resolve(__dirname, "./build")));
// Step 2:


app.get('*', function(req, res) {
  res.sendFile(path.join(__dirname, './build/index.html'));
});

app.listen(4000, () => {
  console.log(`server running on port 4000`);
});

and, package.json

{
  "name": "app",
  "version": "0.1.0",
  "private": true,
  "dependencies": {
    "@testing-library/jest-dom": "^5.16.4",
    "@testing-library/react": "^13.1.1",
    "@testing-library/user-event": "^13.5.0",
    "react": "^18.0.0",
    "react-dom": "^18.0.0",
    "react-scripts": "5.0.1",
    "web-vitals": "^2.1.4"
  },
  "scripts": {
    "start": "react-scripts start",
    "build": "react-scripts build",
    "test": "react-scripts test",
    "eject": "react-scripts eject"
  },
  "eslintConfig": {
    "extends": [
      "react-app",
      "react-app/jest"
    ]
  },
  "browserslist": {
    "production": [
      ">0.2%",
      "not dead",
      "not op_mini all"
    ],
    "development": [
      "last 1 chrome version",
      "last 1 firefox version",
      "last 1 safari version"
    ]
  }
}

404 - NotFound enter image description here

enter image description here

1 Answers

To make it simple, each request is basically followed by url/route/end-point

https://deploy-mern-2084.herokuapp.com/articles/somthing_else

"something_else" should be replaced with one of your endpoint from your nodejs code at your route file

Please, make sure that your node js is not running at the same url with you react js code

Related