Failing to fetch data | Only affects mobile | Express / Postgres / Vue - node.js

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.

Related

Deploying from Local Host to Heroku (Axios Request setup)

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.

Serving Static file publically in nodejs :- Not Working

In my nodejs server file, I am trying to server static folder the code goes as below :-
server.js
const express = require("express");
const app = express();
require("dotenv").config();
const cookieParser = require("cookie-parser");
const bodyParser = require("body-parser");
const { connectDB } = require("./config/connectDB");
connectDB();
const upload = require("./routes/uploadsFile");
const user = require("./routes/user");
const path = require("path");
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(cookieParser());
app.use(express.json("content-type", "application/json"));
const publicFolder = path.join(__dirname, "../uploads");
console.log(publicFolder);
app.use(express.static(publicFolder));
app.use("/api/v1/upload", upload);
app.use("/api/v1/user", user);
const PORT = process.env.PORT || 3030;
app.listen(PORT, () => {
console.log(`Server Started Listening On PORT ${PORT}`);
});
The folder structures goes below :-
The same error I am getting as everyone
Cannot GET /uploads/image/actual-size/banner-Image-1.jpg
Can someone please help me. I have gone through many problem already answered like this on Stackoverflow, but unable to get the proper solution.
You defined uploads to be the root directory for serving static files which means the request paths must not start with /uploads. In your example above change the path to:
/image/actual-size/banner-Image-1.jpg
From the docs:
Express looks up the files relative to the static directory, so the
name of the static directory is not part of the URL.
I got the solution of the problem.
I was calling the GET URL by
localhost:${port}/uploads/image/actual-size/image.jpg
But I had to call like this because uploads folder is being server by default
localhost:${port}/image/actual-size/image.jpg

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?)

Unable to load data from MongoDB Atlas from heroku app after succesful deployment

I am a beginner to MERN stack development.I have deployed my nodejs app without any error on heroku.But the app does not load the data from mongodb atlas database.The app connects to database and displays the data without any problem when run locally.Any ideas on how to fix this?
I have already added environment variable on heroku and whitelisted all ip addressed on atlas.But still the app does not load data from the database
server.js
const express = require('express'); //nodejs framework for creating web apps
const cors = require('cors');
const mongoose = require('mongoose');
const path = require('path');
require('dotenv').config(); //for setting environment variables on server
const app = express(); //creating the app
//Serve static assets if in production
if(process.env.NODE_ENV ==='production'){
//Set static folder
app.use(express.static('client/build'));
app.get('*',(req, res) => {
res.sendFile(path.resolve(__dirname,'client','build','index.html'));
});
}
////////////////////////////////////////
const port = process.env.PORT || 5000;
app.use(cors()); //for cross origin resource sharing ie.cross domain requests
app.use(express.json()); //for handling json data
const uri = process.env.ATLAS_URI;
mongoose.connect(uri,{ useNewUrlParser: true, useCreateIndex: true ,useUnifiedTopology: true });
const connection = mongoose.connection;
connection.once('open',() => {
console.log('Database connection established successfully');
})
const exercisesRouter = require('./routes/exercises');
const usersRouter = require('./routes/users');
//executes the files in the second argument when user enters the url 'rooturl/firstargument'
app.use('/exercises',exercisesRouter);
app.use('/users',usersRouter);
app.listen(port,() => {
console.log(`Server is running on port:${port}`);
});
http://justworkout.herokuapp.com/
This is the app url
The list of exercises should load from the database but nothing is loaded as you can see
I had the same problem. The solution for me it was to go to my client folder and change all my fetch methods. For fetching data I'm using axios. I was sending request to localhost:5000 and then /api/etc. The request was something like this:
axios.get("http://localhost:5000/apps/blog").then()
To make it work on heroku I needed to remove the prefix of localhost and leave just the api path.
axios.get("/apps/blog").then()
Changing this sort my problem.

Node.js server app using cors, express and google api not working after azure deployment

I have a node.js server api app that is not working after being deployed to azure.
It initially relies on google.api to get the data and after that stores the data in an array and sends it to client by responding to express get calls.
Initially I used:
const express = require('express');
const app = express();
const cors = require("cors");
const _ = require("lodash");
const port = 30000;
app.use(cors());
which worked well enough on localhost.
For deployment, after following a tutorial I changed that to:
const express = require('express');
const app = express();
const cors = require("cors");
const _ = require("lodash");
const port = process.env.PORT || 80;
var http = require('http');
app.use(cors());
var server = http.createServer(app);
server.listen(port, function () {
});
which did not work and finally:
const express = require('express');
const app = express();
const _ = require("lodash");
const port = process.env.PORT || 80;
var login = require('./routes/login');
...
app.use('/login', login);
...
module.exports = app;
and created a new folder for the get commands, as is done here https://github.com/Azure-Samples/app-service-web-nodejs-get-started/blob/master/app.js.
Nothing seems to work and I continue to get the error:
GET http://nameofsite/login 404 (Not Found)
XMLHttpRequest cannot load nameofsite/login. No
'Access-Control-Allow-Origin' header is present on the requested
resource. Origin 'nameofclient' is therefore not allowed access. The
response had HTTP status code 404.
I have tried including the cors header as well as adding the client site to cors allowed origins in the azure portal but it makes no difference. Can anyone help with this issue or provide info on how to correctly format a node.js server using info from a google sheets document?
This might be a silly question but when you moved the VM to Azure did you setup your ip address, update your external DNS and configure the virtual network to allow the correct traffic that Node and your code needs?

Resources