Deploying from Local Host to Heroku (Axios Request setup) - node.js

I have a react & node.js app that passes data from a form on the client side to server side via an axios POST request and receives a response. I'm trying to set this up on Heroku. On my local system it works perfectly but I can't seem to get it functional on Heroku. It renders the react app but errors on the axios request when the form is submitted which returns error 500 at /api:
const response = await axios.post('/api', poem);
In my local system I was able to use:
const response = await axios.post('https://localhost:3001/api', poem);
... but obviously this won't work in Heroku. Locally the react app would run on https://localhost:3000/ and the server on https://localhost:3001/. All my research says it should work with just the '/api' because it will default to https://my-app.herokuapp.com/api but I get an internal server error at that https://my-app.herokuapp.com/api.
My server.js file looks like this:
// server.js
const PORT = process.env.PORT || 3001;
const express = require("express");
//const cors = require("cors");
const axios = require("axios");
const fetch = require('node-fetch');
const path = require('path');
require('dotenv').config();
const app = express();
app.use(express.static(__dirname + '/'));
if (process.env.NODE_ENV === 'production') {
app.use(express.static('build'));
app.get('*', (req, res) => {
res.sendFile(path.join('build', 'index.html'));
});
}
And here is my file structure: file structure.

Related

Why ECONNRESET error is coming in POSTMAN while making a NODEJS request

I have written a simple request response code in NODEJS but there is no response in return of the request is there .
The code for my app.js(Server file) is
const express = require('express');
const cors = require('cors')
const paymentroute = require('./routes/paymentRoutes');
const app = express();
app.use(cors);
app.use("/api",paymentroute);
app.listen(3100,()=>{
console.log(`listening to port 3100`);
})
The code for my req and res is
const express = require('express');
const router = express.Router();
// const { checkout } = require('../controllers/paymentController');
router.post("/checkout",(req,res) => {
console.log("this function is called ")
return res.json({success:"true"})
});
module.exports = router;
Even the console.log inside the res function is not working.
Just change app.use(cors); to app.use(cors());
const express = require('express');
const cors = require('cors');
const paymentroute = require('./routes/paymentRoutes');
const app = express();
app.use(cors());
app.use('/api', paymentroute);
app.listen(3100, () => {
console.log(`listening to port 3100`);
});
I think it is a connection-related issue often related to a networking issue caused by a Virtual Private Network (VPN) that in some cases is required by some API services or, in other cases, prevents you to reach an API service.
The issue seems to be a combo of having the no-cache header enabled and a request URL length over 64 characters. If the issue persists after doing this solution then try to upgrade to the latest version of Postman.

Getting 404 when hitting API URL from react to node in production

I have a backend for the frontend framework for my app. On local, I am able to hit API URL from React to Node, but when I am deploying my app to prod, it is throwing me 404. I am currently using netlify to deploy my changes and checking them. Below is the code I am using in local to hit the API,
React-
const response = await fetch('http://localhost:5000/fetchData');
Node-
const express = require('express');
const cors = require('cors');
const axios = require('axios');
const port = 5000;
const app = express();
app.use(cors());
app.get('/fetchData', async (req, res) => {
const apiResponse = await axios.get(
'https://jsonplaceholder.typicode.com/posts'
);
res.send(apiResponse.data);
});
app.listen(port, () => {
console.log('Server is up');
});
While building this code for prod, I am removing http://localhost:5000 from the URL on React side and hitting the endpoint like this,
const response = await fetch('/fetchData');
But I am getting 404, could someone help where I am going wrong and how to hit the URL properly?
Your issue is that by using
const response = await fetch('/fetchData');
You are requesting using the frontend domain/ip.
So if the frontend domain was example.com, you are trying to access https://example.com/fetchData, I'm guessing you need to access https://api.example.com/fetchData. I'd recommend using an axios instance to add the base URL once only.

How to build server.js express server around a remote github page JSON object

I have a GitHub page with one file in it: model.json. In model.json is a JSON object. I'd like to be able to access that object via a fetch request triggered in the frontend of my app.
However, I have only done mock localhost express server.jses thus far, and I don't know how to point the server.js file at a remote server.
That is, typically what I have done is something like this:
const express = require("express");
const bodyParser = require("body-parser");
const CORS = require("cors");
const app = express();
app.use(bodyParser.json());
app.use(CORS());
let modelObj = modelJSON;
// ^this "modelJSON" would be the json object in question,
// whether accessed remotely or locally.
app.get("/model.json", (req, res) => {
res.send(modelObj);
});
app.listen(5000, () => {
console.log("Server listening on port 5000");
});
I'm wondering how to make this listen to my https://<my-github-username>.github.io page instead of port 5000.
(Incidentally, will I want this server.js file in my local project/app file or in the github page root directory?)

How to deploy reactJS app with json-server

I have actually deployed my React-app in the following way:-
ran the command: npm run build
Already had db.json file with dummy data.
Context, when I run
json-server --watch db.json -p 3001 -d 2000
the entire react-app works on the localhost
installed json-server using npm
created a server.js file
const jsonServer = require('json-server');
const server = jsonServer.create();
const router = jsonServer.router('db.json');
const middlewares = jsonServer.defaults();
const port = process.env.PORT || 3001;
server.use(middlewares);
server.use(router);
server.listen(port);
created the app on heroku and pushed it to heroku master
The website for some reason only works when I run node server.js on my local-machine and it is making requests to my localport.
if that command isn't running the react-app cannot do the axios request to the DB.
I don't know what went wrong.
I used the following tutorial for this: https://github.com/jesperorb/json-server-heroku
My suspicions are that in my code I have created a basUrl.js file in which
export const baseUrl = 'http://localhost:3001/';
How should I change this to fix my problem?
Thanks for your help.
You should link your react folder built with the server (server.js), to do that add:
const express = require('express');
const path = require('path');
app.use(express.static(path.join(__dirname, 'build')));
app.get('/*', function (req, res) {
res.sendFile(path.join(__dirname, 'build', 'index.html'));
});
'build' is your react app's folder created after npm run build into your react app folder.
You have to install path and express modules if not.
And, You should get your json-server database in 'get' function, to use it with a specific url like: /db, just like this:
app.use('/db', middlewares, router);
But you should put /db before /* to not to open database with url /.
So, the result (server.js) will be:
const jsonServer = require('json-server');
const app = jsonServer.create();
const path = require('path');
const express = require('express');
const middlewares = jsonServer.defaults();
const router = jsonServer.router('db.json');
const port = process.env.PORT || 3001;
app.use('/db', middlewares, router);
app.use(express.static(path.join(__dirname, 'build')));
app.get('/*', function (req, res) {
res.sendFile(path.join(__dirname, 'build', 'index.html'));
});
server.listen(port);
I have Heroku running on my JSON server too. You need to correct your API path to be your resource name, for example;
If your resource name in your API is 'blogs';
{
"blogs": [
{
"postTitle": "My First Blog",
then your api path will be;
https://xxxx.herokuapp.com/blogs
OR
export const baseUrl = 'https://xxxx.herokuapp.com/blogs';
You shouldn't need to specify a port, but if you do it will be port 4000, which Heroku uses.

Failing to fetch data | Only affects mobile | Express / Postgres / Vue

My Vue app runs perfectly on desktop, but on mobile, it fails to fetch data when the app loads, leaving the components rendering but with no data to display.
Link to the app
Link to the entire Github repository
I diagnosed the issue by running it through Google's Mobile-Friendly Test tool: here are the results.
My index.js looks like this:
const express = require("express");
const serveStatic = require("serve-static");
const bodyParser = require("body-parser");
const cors = require("cors");
const db = require("./queries");
const app = express();
app.use(serveStatic(__dirname + "/dist"));
app.use(cors());
app.use(bodyParser.json());
app.get("/sizemenudata", db.getSizeMenuData);
app.get("/lightlevelmenudata", db.getLightLevelMenuData);
app.get("/easeofcaremenudata", db.getEaseOfCareMenuData);
app.get("/petsafemenudata", db.getPetSafeMenuData);
app.get("/menuTitles", db.getMenuTitles);
app.use(express.static("dist"));
const port = process.env.PORT || 3000;
app.listen(port, () => {
console.log(`Listening on ${port}`);
});
Things to note:
I'm fetching the data from a postgres database, here is my sql file.
I have a seperate queries.js file which I import into index.js.
Closing this because it was a simple error, the Heroku ENV vars weren't set.

Resources