basic nodejs and express server setup not working - node.js

This should be very simple, steps I took:
1)used vue cli3 to create vue project (that worked fine).
2)created a server folder on the root level
3)created an index.js file
4)created api/routes/users.js
I am getting in the browser at http://localhost:4000/api/add Cannot GET api/add.
Here is my index file:
const express = require('express');
const bodyParser = require('body-parser');
const cors = require('cors');
const app = express();
//middleware
app.use(bodyParser.json());
app.use(cors());
const users = require('./api/routes/users');
app.use('api/add', users);
const port = process.env.PORT || 4000;
app.listen(port, () => console.log(`Listening on port ${port}...` ));
Below this is my users.js file:
const mongodb = require('mongodb');
const router = express.Router();
router.get('/', (req, res) => {
res.send('hello');
})
module.exports = router;
Here is what my package JSON looks like, not sure if this somehow creates problems since I first made the frontend and then started the backend.
{
"name": "fastpo",
"version": "0.1.0",
"private": true,
"scripts": {
"serve": "vue-cli-service serve",
"start": "node server/index.js",
"dev": "nodemon server/index.js",
"build": "vue-cli-service build",
"lint": "vue-cli-service lint"
},
"dependencies": {
"axios": "^0.18.0",
"body-parser": "^1.18.3",
"cors": "^2.8.5",
"express": "^4.16.4",
"mongoose": "^5.4.11",
"morgan": "^1.9.1",
"nodemon": "^1.18.10",
"serve-favicon": "^2.5.0",
"vue": "^2.5.22",
"vue-compose": "^0.7.1",
"vuetify": "^1.3.0"
},
"devDependencies": {
"#vue/cli-plugin-babel": "^3.4.0",
"#vue/cli-plugin-eslint": "^3.4.0",
"#vue/cli-service": "^3.4.0",
"babel-eslint": "^10.0.1",
"eslint": "^5.8.0",
"eslint-plugin-vue": "^5.0.0",
"stylus": "^0.54.5",
"stylus-loader": "^3.0.1",
"vue-cli-plugin-vuetify": "^0.4.6",
"vue-template-compiler": "^2.5.21",
"vuetify-loader": "^1.0.5"
},
"eslintConfig": {
"root": true,
"env": {
"node": true
},
"extends": [
"plugin:vue/essential",
"eslint:recommended"
],
"rules": {},
"parserOptions": {
"parser": "babel-eslint"
}
},
"postcss": {
"plugins": {
"autoprefixer": {}
}
},
"browserslist": [
"> 1%",
"last 2 versions",
"not ie <= 8"
]
}

Forgot to add "/" here before api: app.use('api/add', users);
should be app.use('/api/add', users)

Related

NodeJs send you need to enable javascript on certain request

I have a Nodejs API that sends responses to a react application.
When I send a request for user information on login, the request succeeds and I get back a proper response. The thing is after I sent an initial request to log in, I get back the this response.
You need to enable JavaScript to run this app.
This only happens in production. Locally it's fine. Even doing a production build locally works just fine. It's only when I deploy to my AWS containers.
Here is my API package.json
{
"name": "my-api",
"version": "0.0.0",
"private": true,
"scripts": {
"dev": "nodemon ./bin/www",
"prod": "sudo forever stopall && forever start ./bin/www",
"start": "node ./bin/www",
"seed": "node ./setup/seed.js"
},
"engines": {
"node": ">= 12.0.0"
},
"dependencies": {
"aws-sdk": "^2.738.0",
"bcryptjs": "^2.4.3",
"bluebird": "^3.7.2",
"body-parser": "^1.19.0",
"braintree": "^3.5.0",
"compression": "^1.7.4",
"connect-pg-simple": "^6.2.1",
"cookie-parser": "~1.4.4",
"cors": "^2.8.5",
"debug": "~2.6.9",
"express": "^4.16.4",
"express-session": "^1.17.1",
"file-type": "^14.7.1",
"formik": "^2.1.4",
"fs": "0.0.1-security",
"http-errors": "~1.6.3",
"jade": "~1.11.0",
"multiparty": "^4.2.2",
"nodemailer": "^6.6.2",
"nodemailer-smtp-transport": "^2.7.4",
"nodemon": "^2.0.4",
"pg": "^8.2.1",
"pg-hstore": "^2.3.3",
"pg-transaction": "^1.0.4",
"uuid": "^8.3.2",
"winston": "^3.3.3"
}
}
Here is my application API.
const httpProxy = require("http-proxy");
const https = require("https");
const fs = require("fs");
const appConfig = require("./config");
const appPath = `./app.${appConfig.isProduction ? "prod" : "dev"}`;
const logger = require("./utils/logger");
const app = require(appPath);
const apiProxy = httpProxy.createProxyServer();
const ACUTAL_API = process.env.ACTUAL_API || "http://localhost:8181";
app.set("x-powered-by", false);
app.all("/api/*", function (req, res) {
logger.info("reverse proxying to api");
console.log("reverse proxying");
apiProxy.web(req, res, { target: ACTUAL_API });
});
if (!appConfig.isProduction) {
app.listen(appConfig.port, () => {
logger.info(`Server started at: http://localhost:${appConfig.port}`);
});
} else {
https
.createServer(
{
/* Certificate Managed By AWS ACM */
key: fs.readFileSync("./certificates/localhost.key"),
cert: fs.readFileSync("./certificates/localhost.crt"),
passphrase: "",
},
app
)
.listen(appConfig.port);
}
Application API app.prod.js
const express = require("express");
const app = express();
const path = require("path");
const BUILD_DIR = path.join(__dirname, "../build/");
console.log(BUILD_DIR);
app.use(express.static(BUILD_DIR));
const HTML_FILE = path.join(BUILD_DIR, "index.html");
app.get("*", (req, res) => res.sendFile(HTML_FILE));
module.exports = app;
Application API Package.json
{
"name": "proxy-server",
"version": "1.0.0",
"description": "proxy server for web",
"main": "index.js",
"scripts": {
"start": "nodemon ./",
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "YoMommasKrypton",
"license": "ISC",
"dependencies": {
"babel-register": "^6.26.0",
"body-parser": "^1.19.0",
"cookie-parser": "^1.4.5",
"express": "^4.17.1",
"express-http-proxy": "^1.6.2",
"glob": "^7.1.6",
"node-env-file": "^0.1.8",
"winston": "2.3.1"
},
"devDependencies": {
"nodemon": "^2.0.7"
}
}

I want to deploy my React application on Heroku but I am getting the error cannot get/ after my application is deployed

Picture of my React application with all the files
My src files
I am unable to deploy my application on Heroku.
My package.json for outer (backend) file
{
"name": "teams-clone",
"version": "1.0.0",
"description": "",
"main": "server.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"start": "node server.js && cd client && npm start"
},
"author": "",
"license": "ISC",
"dependencies": {
"body-parser": "^1.19.0",
"cors": "^2.8.5",
"dotenv": "^10.0.0",
"express": "^4.17.1",
"redis": "^3.1.2",
"socket.io": "^4.1.2"
}
}
My server.js file
require("dotenv").config();
const express = require("express");
const http = require("http");
const bodyParser = require("body-parser");
const cors = require("cors");
const port = process.env.PORT;
const app = express();
const server = http.createServer(app);
const Routes = require("./app/routes");
app.use([
cors(),
bodyParser.json(),
bodyParser.urlencoded({ extended: false }),
Routes,
]);
const io = (module.exports.io = require("socket.io")(server, {
cors: {
origin: "*",
},
}));
const socketManager = require("./app/socketManager");
io.on("connection", socketManager);
server.listen(port, () => {
console.log(`Server is running on port ${port}`);
});
My client package.json file:
{
"name": "client",
"version": "0.1.0",
"private": true,
"dependencies": {
"#fortawesome/fontawesome-svg-core": "^1.2.35",
"#fortawesome/free-solid-svg-icons": "^5.15.3",
"#fortawesome/react-fontawesome": "^0.1.14",
"#syncfusion/ej2-react-schedule": "^19.1.69",
"#testing-library/jest-dom": "^5.14.0",
"#testing-library/react": "^11.2.7",
"#testing-library/user-event": "^12.8.3",
"axios": "^0.21.1",
"date-fns": "^2.22.1",
"ejs": "^3.1.6",
"express": "^4.17.1",
"moment": "^2.29.1",
"node-sass": "^4.14.1",
"react": "^17.0.2",
"react-calendar": "^3.4.0",
"react-dom": "^17.0.2",
"react-icons": "^4.2.0",
"react-router-dom": "^5.2.0",
"react-scripts": "4.0.3",
"shortid": "^2.2.16",
"simple-peer": "^9.11.0",
"socket.io": "^4.1.2",
"socket.io-client": "^4.1.2",
"web-vitals": "^1.1.2"
},
"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"
]
}
}
I also have this piece of code for socket connections in my client:
let peer = null;
const socket = io.connect("http://localhost:4000");
const initialState = [];
I have changed it to the heroku link while deploying instead of local host 4000
my apiEndpints BASE_URL now is:
http://localhost:4000
which I changed it to the heroku link while deploying instead of local host 4000
How my application starts is:
first switch on Redis.exe -> node server.js -> cd client -> npm start
I also made a Procfile with=> web: node server.js
What am I doing wrong?

React front end connects to the development server on my computer instead of the Node server on Azure VM where it is hosted from why using localhost

I have a React front end and Node with Express server. When I build and run it on my computer everything works perfect. When I build and run it on my Azure Ubuntu VM the server starts successfully and it hosts the React front end and I can access it no problem. But I get a "net::ERR_CONNECTION_REFUSED" in the console when it tries to access the node server. I then noticed that if my server was running on my computer the React app hosted on the Azure VM would hit the server on my local computer and not the one on the Azure VM.
So, how do I get the React app hosted on the VM to properly point to the server/vm it is hosted from?
The file structure of the app is:
>App Root
>client
>build
>public
>src
>components
>reducer, assets, middleware, services
App.js
http-common.js
index.js
package.json
>server
>config, controllers, models, routes
package.json
server.js
server.js
const bodyParser = require("body-parser");
const cors = require("cors");
const morgan = require('morgan');
const path = require('path');
const app = express();
app.use(cors());
app.use(bodyParser.json());
app.use(express.static(__dirname + '/client/build'));
app.use(morgan('dev'));
app.use(bodyParser.urlencoded({ extended: true }));
const db = require("./server/models");
db.sequelize.sync();
require("./server/routes/h.routes")(app);
require("./server/routes/p.routes")(app);
require("./server/routes/user.routes")(app);
app.get('/*', function(req, res) {
res.sendFile(path.join(__dirname, '/client/build/index.html'), function(err) {
console.log('In sendFile of get /*')
if (err) {
console.log('error: ', err)
res.status(500).send(err)
}
})
})
const port = 5000;
app.listen(port, () => console.log(`Listening on port ${port}`));
server package.json
"name": "test",
"version": "1.0.0",
"description": "",
"main": "server.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"start": "node server.js",
"start:dev": "nodemon server.js"
},
"author": "",
"license": "ISC",
"dependencies": {
"body-parser": "^1.19.0",
"cors": "^2.8.5",
"express": "^4.17.1",
"morgan": "^1.10.0",
"mysql": "^2.18.1",
"mysql2": "^2.2.5",
"path": "^0.12.7",
"react": "^17.0.2",
"react-dom": "^17.0.2",
"react-redux": "^7.2.3",
"redux": "^4.0.5",
"sequelize": "^6.6.2"
},
"devDependencies": {
"nodemon": "^2.0.7"
}
"proxy": "http://localhost:5000"
}
http-common.js
export default axios.create({
baseURL: "http://localhost:5000/api",
headers: {
"Content-type": "application/json",
},
});
client package.json
"name": "tissue-screener",
"version": "0.1.0",
"private": true,
"dependencies": {
"#material-ui/core": "^4.11.3",
"#material-ui/lab": "^4.0.0-alpha.57",
"#testing-library/jest-dom": "^5.11.10",
"#testing-library/react": "^11.2.6",
"#testing-library/user-event": "^12.8.3",
"axios": "^0.21.1",
"bootstrap": "^4.6.0",
"dotenv": "^8.2.0",
"msal": "^1.4.10",
"react": "^17.0.2",
"react-beautiful-dnd": "^13.1.0",
"react-dom": "^17.0.2",
"react-redux": "^7.2.3",
"react-router-dom": "^5.2.0",
"react-scripts": "4.0.3",
"redux": "^4.0.5",
"redux-devtools-extension": "^2.13.9",
"redux-thunk": "^2.3.0",
"web-vitals": "^1.1.1"
},
"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"
]
},
"main": "../server.js",
"proxy": "http://localhost:5000"
}
I figured out the answer and decided to share it here in case anyone else makes the same dumb mistake I did.
http-common.js
export default axios.create({
baseURL: "/api",
headers: {
"Content-type": "application/json",
},
});
That's it. Just had to remove the "http://localhost:5000" from the axios.create and let the proxy setting in the package.json do it's work.

Deployed my app on heroku but got error: Failed to load resource: net::ERR_CONNECTION_REFUSED

My app's front-end is Reactjs and backend is Node js. I used express server and graphql-express server. I deployed my app successfully. But it starts with data is loading and then nothing shows. But if I run locally npm start then the heroku app is start working.
This is the error I get it in browser
This is my server's package json file. If i run in terminal npm run dev. It opens my react js app.
{
"name": "backend",
"version": "1.0.0",
"description": "personish vol 2",
"main": "server.js",
"scripts": {
"start": "node server.js",
"server": "node server.js",
"client": "npm start --prefix client",
"dev": "concurrently \"npm run server\" \"npm run client\""
},
"author": "Alak",
"license": "ISC",
"dependencies": {
"concurrently": "^5.0.2",
"cors": "^2.8.5",
"express": "^4.17.1",
"express-graphql": "^0.9.0",
"graphql": "^14.5.8",
"pg": "^7.15.1",
"pg-hstore": "^2.3.3",
"sequelize": "^5.21.3"
}
}
This is my react's package json
{
"name": "client",
"version": "0.1.0",
"private": true,
"engines": {
"node": "13.3.0",
"npm": "6.13.0"
},
"dependencies": {
"#testing-library/jest-dom": "^4.2.4",
"#testing-library/react": "^9.3.2",
"#testing-library/user-event": "^7.1.2",
"apollo-boost": "^0.4.7",
"axios": "^0.19.0",
"firebase": "^7.6.1",
"graphql": "^14.5.8",
"pg": "^7.15.1",
"react": "^16.12.0",
"react-apollo": "^3.1.3",
"react-dom": "^16.12.0",
"react-dropzone": "^10.2.1",
"react-redux": "^7.1.3",
"react-redux-firebase": "^3.0.5",
"react-router-dom": "^5.1.2",
"react-scripts": "3.3.0",
"redux": "^4.0.4",
"redux-firestore": "^0.11.0",
"redux-thunk": "^2.3.0"
},
"scripts": {
"start": "react-scripts start",
"build": "react-scripts build",
"test": "react-scripts test",
"eject": "react-scripts eject"
},
"eslintConfig": {
"extends": "react-app"
},
"browserslist": {
"production": [
">0.2%",
"not dead",
"not op_mini all"
],
"development": [
"last 1 chrome version",
"last 1 firefox version",
"last 1 safari version"
]
}
}
This is my express and graphql-express server.
const express = require("express");
const app = express();
const graphqlHTTP = require("express-graphql");
const schema = require("./schema");
const cors = require("cors");
const path = require("path");
app.use(cors());
app.use(
"/graphql",
graphqlHTTP({
schema,
pretty: true,
graphiql: true
})
);
app.use(express.static(path.join(__dirname, "build")));
app.get("/*", (req, res) => {
res.sendFile(path.join(__dirname, "build", "index.html"));
});
const port = process.env.PORT || 8081;
app.listen(port, () =>
console.log(`✅ Example app listening on port ${port}!`)
);
This is my react's app file. Where I use Apollo boost to connect with react app and node js app. I think the error comes from here, dont know how to fix it
import React from "react";
import { ApolloClient, HttpLink, InMemoryCache } from "apollo-boost";
import { ApolloProvider } from "react-apollo";
const client = new ApolloClient({
link: new HttpLink({
uri: "http://localhost:8081/graphql"
}),
cache: new InMemoryCache()
});
This is my heroku app
https://databaseapp2020.herokuapp.com/
your heroku dyno/app would have a name, you would use that to hit your graphql from say a graphiql playground on your laptop, or your react-app... if your heroku app was actually named databaseapp2020 and running then you would use the following assuming your cors was setup properly in the dyno environment variables
https://databaseapp2020.herokuapp.com/graphql

I get 404 error in the localhost even though I already did "npm run build"

I'm trying to send a small demo made with React to production. I did not make the demo with create-react-app, I did it by hand. I used express.js to serve the application.
When I run the command "SET NODE_ENV = production node server.js" (I'm in Windows, that's why SET) and I go to the localhost I keep getting GET / 404, even though I already made the command "npm run build".
Since it's the first time I do this, I really have no clue what happens.
This is my package.json:
{
"name": "app",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"build": "webpack --colors",
"serve": "webpack-dev-server --content-base build/ --color --
progress",
"start": "npm run build && npm run serve",
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "Pepe",
"license": "MIT",
"devDependencies": {
"babel-cli": "^6.26.0",
"babel-core": "^6.26.0",
"babel-eslint": "^8.2.2",
"babel-loader": "^7.1.2",
"babel-preset-env": "^1.4.0",
"babel-preset-react": "^6.24.1",
"babel-preset-stage-2": "^6.24.1",
"css-loader": "^0.28.9",
"eslint": "3.15.0",
"eslint-config-airbnb": "14.1.0",
"eslint-loader": "^1.9.0",
"eslint-plugin-import": "2.2.0",
"eslint-plugin-jsx-a11y": "4.0.0",
"eslint-plugin-react": "6.10.0",
"extract-text-webpack-plugin": "^3.0.2",
"html-webpack-plugin": "^2.30.1",
"identity-obj-proxy": "^3.0.0",
"jshint": "^2.9.6",
"style-loader": "^0.20.2",
"url-loader": "^0.5.8",
"webpack": "^3.3.0",
"webpack-dev-server": "^2.9.7"
},
"dependencies": {
"bootstrap": "^4.0.0",
"compression": "^1.7.3",
"express": "^4.16.4",
"mime": "^1.4.1",
"morgan": "^1.9.1",
"normalize.css": "^8.0.0",
"react": "^16.2.0",
"react-dom": "^16.2.0",
"react-router-dom": "^4.1.1",
"uuid": "^3.2.1"
},
"standard": {
"ignore": [
"/build/"
]
},
"eslintConfig": {
"extends": [
"standard",
"standard-jsx"
]
},
"stylelint": {
"extends": "stylelint-config-standard"
},
"optionalDependencies": {
"win-node-env": "^0.4.0"
}
}
And here is my server.js:
const { createServer } = require('http');
const express = require('express');
const compression = require('compression');
const morgan = require('morgan');
const path = require('path');
const normalizePortprocess = port => parseInt(port, 10);
const PORT = normalizePortprocess(process.env.PORT || 3000);
const app = express();
const dev = app.get('env') !== 'production';
if (!dev) {
app.disable('x-powered-by');
app.use(compression());
app.use(morgan('common'));
app.use(express.static(path.resolve(__dirname, 'build')));
app.get('*', (req, res) => {
res.sendFile(path.resolve(__dirname, 'build', 'index.html'));
});
}
if (dev) {
app.use(morgan('dev'));
}
const server = createServer(app);
server.listen(PORT, err => {
if(err) throw new err;
console.log(`Server listen in ${PORT}`);
});
Everything would seem to work correctly except that despite having executed to many times the command "npm run build", still nothing appears
You are running in a development environment, and only handling that GET request if !dev.
if (!dev) { // here is the problem
// ...
app.get('*', (req, res) => {
res.sendFile(path.resolve(__dirname, 'build', 'index.html'));
});
}
Instead, either remove the if statement and always handle this route, or change it to if(dev).

Resources