NODE API runs on localhost but doesn't run on Vercel - node.js

I'm trying to upload a node app to Vercel and use as API but I'm getting an This Serverless Function has crashed. error message. The fact that I can run it with no problems in localhost, and the fact that the build log doesn't throw an error, I can't seems to find the problem.
Here is a full Screenshot:
vercel app
And here is my index.js:
const express = require(`express`);
var cors = require('cors')
const app = express();
app.use(cors())
const bodyParser = require('body-parser')
const mongoose = require("mongoose")
require("dotenv").config();
const config = require('config');
const dbConfig = config.get("MT.dbConfig.dbName")
mongoose.connect(dbConfig, {
}).then(() => {
console.log('Database connected.')
}).catch((err)=> console.log('Something went wrong with the database : ' + err))
mongoose.Promise = global.Promise;
app.use(bodyParser.json())
app.use('/', require('./api/v1/api'))
app.use((err, req, res, next) =>{
res.status(422).send({
error: err._message
})
})
const PORT = 5001;
app.listen(PORT, () => console.log("API is running."))
And here is my package.json:
{
"name": "hidden",
"version": "1.0.0",
"description": "",
"main": "index.js",
"engines": {
"node": "14.x"
},
"scripts": {
"start": "vercel dev",
"deploy": "vercel deploy --prod"
},
"author": "hidden",
"license": "ISC",
"dependencies": {
"body-parser": "^1.19.0",
"config": "^3.3.6",
"cors": "^2.8.5",
"dotenv": "^10.0.0",
"express": "^4.17.1",
"mongoose": "^6.0.13",
"vercel": "^23.1.2"
},
"devDependencies": {
"nodemon": "^2.0.15"
}
}

Related

Can't connect pgadmin to the server

I'm trying to connect my server (based on node.js) with db from pgAdmin.<>
However I keep getting '${PORT}', instead of PORT's value in env file :
pgAdmin part:
index.js file:
require('dotenv').config()
const express = require ('express')
const sequelize = require('./db')
const PORT = process.env.PORT || 5000
const app = express()
const start = async () => {
try {
await sequelize.authenticate()
await sequelize.sync()
app.listen(PORT,()=>console.log('Server started on port ${PORT}'))
} catch (e) {
console.log(e)
}
}
start()
db.js:
const {Sequelize} = require('sequelize')
module.exports = new Sequelize(
process.env.DB_NAME,
process.env.DB_USER,
process.env.DB_PASSWORD,
{
dialect:'postgres',
host: process.env.DB_HOST,
port: process.env.DB_PORT
}
)
.env file:
PORT=7000
DB_NAME=postgres
DB_USER=postgres
DB_PASSWORD='Ondj8_oP1sw'
DB_HOST=localhost
DB_PORT=5432
package.json:
"name": "server",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"dev": "nodemon index.js"
},
"keywords": [],
"author": "",
"license": "ISC",
"dependencies": {
"cors": "^2.8.5",
"dotenv": "^16.0.1",
"express": "^4.18.1",
"pg": "^8.8.0",
"pg-hstore": "^2.3.4",
"sequelize": "^6.21.4"
},
"devDependencies": {
"nodemon": "^2.0.19"
}
}
The actual connection should be fine, yet your console.log should look like console.log(`Server started on port ${PORT}`), use back ticks `` if you want to console.log a variable.

Netlify / React front end not connecting to Node.js / Express / MongoDB Atlas / Heroku backend but works in development/locally

FIX: after following some advice I ditched the setupProxy and put the full API urls into the axios request. This threw a cors error so I imported CORS & added app.use(cors()) into my index.js & when I redeployed the app ran as intended
I am trying to deploy a MERN stack practise project for the first time. I am quite a new coder.
My project works perfectly fine in development/locally. My React app running on localhost:3000 connects to the Node/Express/MongoDB Atlas API that I deployed to Heroku & can make requests successfully.
However when I open the deployed Netlify app it fails to load any data & the Heroku logs show no activity which suggests it's not connecting to the backend at all.
Here are some bits of code that may be relevant:
-----------Backend---------------
environment.js (info in <> redacted)
export const dbURI = process.env.MONGODB_URI || 'mongodb+srv://<name>:<password>#festivalist.iyq41.mongodb.net/festivalist?retryWrites=true&w=majority'
export const port = process.env.PORT || 4000
export const secret = process.env.SECRET || '<secret>'
index.js
import express from 'express'
const app = express()
import mongoose from 'mongoose'
import router from './config/router.js'
import { port, dbURI } from './config/environment.js'
const startServer = async () => {
try {
await mongoose.connect(dbURI, { useNewUrlParser: true, useCreateIndex: true, useUnifiedTopology: true })
console.log('🚀 Database has connected successfully')
app.use(express.json())
app.use((req, _res, next) => {
console.log(`🚨 Incoming request: ${req.method} - ${req.url}`)
next()
})
app.use('/api', router)
app.listen(port, () => console.log(`🚀 Express is up and running on port ${port}`))
} catch (err) {
console.log('🆘 Something went wrong starting the app')
console.log(err)
}
}
startServer()
package.json
{
"name": "sei-project-three",
"version": "1.0.0",
"main": "index.js",
"dependencies": {
"bcrypt": "^5.0.1",
"dotenv": "^10.0.0",
"express": "^4.17.1",
"jsonwebtoken": "^8.5.1",
"mongo": "^0.1.0",
"mongoose": "^5.12.0",
"nodemon": "^2.0.14"
},
"type": "module",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"seed": "node db/seeds.js",
"dev": "nodemon",
"start": "node index.js"
},
"devDependencies": {
"eslint": "^7.22.0"
},
"engines": {
"node": "16.8.0"
}
}
-------------Front end --------------
setupProxy.js
const { createProxyMiddleware } = require('http-proxy-middleware')
module.exports = function (app) {
app.use(createProxyMiddleware('/api', { target: 'https://festivalist-api.herokuapp.com', "changeOrigin": true }))
}
example request
const ArtistIndex = () => {
const [artists, setArtists] = useState([])
useEffect(() => {
const getData = async () => {
const { data } = await axios.get('/api/artists')
setArtists(data)
}
console.log('artists2', artists)
getData()
}, [])
package.json
{
"name": "client",
"version": "0.1.0",
"private": true,
"dependencies": {
"axios": "^0.21.1",
"http-proxy-middleware": "^1.0.5",
"mapbox-gl": "^2.2.0",
"react": "^17.0.2",
"react-dom": "^17.0.2",
"react-map-gl": "^5.2.5",
"react-mapbox-gl": "^5.1.1",
"react-router-dom": "^5.2.0",
"react-scripts": "4.0.3",
"sass": "^1.42.1",
"semantic-ui-css": "^2.4.1",
"semantic-ui-react": "^2.0.3"
},
"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"
]
},
"devDependencies": {
"#typescript-eslint/eslint-plugin": "^4.25.0",
"#typescript-eslint/parser": "^4.25.0",
"babel-eslint": "^10.1.0",
"eslint": "^7.27.0",
"eslint-config-react-app": "^6.0.0",
"eslint-plugin-flowtype": "^5.7.2",
"eslint-plugin-import": "^2.23.3",
"eslint-plugin-jsx-a11y": "^6.4.1",
"eslint-plugin-react": "^7.23.2",
"eslint-plugin-react-hooks": "^4.2.0"
}
}
Some notes:
I have whitelisted all IP addresses in MongoDB Atlas 0.0.0.0/0
I'm unsure why but I have to put '/api/' on the end of the heroku api url to get the data ie: https://festivalist-api.herokuapp.com/api/festivals
I added Config Vars in Heroku but I think that stopped my app from working locally so I deleted them. Also not fully sure I understand what they do.
I have been trying to deploy this for days now so any advice would be a help or any troubleshooting tips since I am new to coding! Thanks
You have to put '/api' in at the end of heroku API because that's what you've used in your backend index.js app.use('/api', router)
The problem seems like something to do with the middle-wear setupProxy.js since you can ping the API already. One workaround is to just update your requests to use the full URI. i.e
const ArtistIndex = () => {
const [artists, setArtists] = useState([])
useEffect(() => {
const getData = async () => {
const { data } = await axios.get('https://festivalist-api.herokuapp.com/api/artists')
setArtists(data)
}
console.log('artists2', artists)
getData()
}, [])

nodejs server shows starting up but never starts

I just started learning nodejs and there is some weird error coming when I try to run nodemon server.js command.
Here is my server.js
const express = require("express");
const app = express();
const server = require("http").Server(app);
app.get("/", (req, res) => {
res.status(200).send("Hello World");
});
server.listen(3030);
My VScode terminal shows this but the server never starts.
Here is package.json
{
"name": "video-chat-app",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"start": "nodemon server.js"
},
"author": "",
"license": "ISC",
"dependencies": {
"ejs": "^3.1.6",
"express": "^4.17.1",
"peer": "^0.6.1",
"socket.io": "^4.1.2",
"uuid": "^8.3.2"
},
"devDependencies": {
"nodemon": "^2.0.7"
}
}
You don't need to use http, express is already enough to start a server.
const express = require("express");
const app = express();
app.get("/", (req, res) => {
res.status(200).send("Hello World");
});
app.listen(3030, ()=>{
console.log('Server is starting');
});

front end not being deployed in Heroku

I'm trying to deploy my first MERN website to heroku. I have been following different tutorials but I am having trouble connecting the front end with the back end, although they connect fine in development mode.
Just to clarify: the only one that is bein deployed is the server side. I am not being able to deploy the front end.
client's package.json proxy:
"proxy": "http://localhost:5000"
Server package.json:
{
"name": "pictshare",
"version": "1.0.0",
"description": "Image Sharing Application",
"main": "server.js",
"scripts": {
"start": "node server.js",
"server": "nodemon server",
"build": "cd client && npm run build",
"install-client":"cd client && npm install",
"heroku-postbuild":"npm run install-client && npm run build",
"client": "npm start --prefix client",
"dev": "concurrently -n 'server,client' -c 'red, green' \"npm run server\" \"npm run client\""
},
"author": "",
"license": "MIT",
"dependencies": {
"bcryptjs": "^2.4.3",
"body-parser": "^1.19.0",
"config": "^3.3.1",
"ejs": "^3.0.2",
"express": "^4.17.1",
"express-validator": "^6.4.0",
"form-data": "^3.0.0",
"gravatar": "^1.8.0",
"gridfs-stream": "^1.1.1",
"jsonwebtoken": "^8.5.1",
"merge-images": "^1.2.0",
"method-override": "^3.0.0",
"moment": "^2.24.0",
"mongoose": "^5.9.7",
"multer": "^1.4.2",
"multer-gridfs-storage": "^4.0.2",
"node": "^13.12.0",
"nodemailer": "^6.4.6",
"path": "^0.12.7",
"react-draggable": "^4.2.0",
"request": "^2.88.2"
},
"devDependencies": {
"concurrently": "^5.1.0",
"minimist": "^1.2.5",
"nodemon": "^2.0.2"
}
}
Server.js:
const express = require('express');
const connectDB = require('./config/db');
const app = express();
const bodyParser = require('body-parser')
connectDB();
//Initialize Middleware
app.use(express.json({ extended: false }));
app.use(bodyParser.urlencoded({ extended: false }))
app.get('/', (req, res) => res.send('API Running'));
...
app.use('/api/posts', require('./routes/api/posts'));
if (process.env.NODE_ENV === 'production'){
app.use(express.static('client/build'))
}
const PORT = process.env.PORT || 5000;
app.listen(PORT, () => console.log(`Server started on port ${PORT}`));
Mongoose:
const mongoose = require('mongoose');
const config = require('config');
const db = process.env.MONGODB_URI || config.get('mongoURI');
const connectDB = async () => {
try {
await mongoose.connect(db, {
useNewUrlParser: true,
useCreateIndex: true,
useFindAndModify: false,
useUnifiedTopology: true,
useNewUrlParser: true,
});
console.log('MongoDB Connected...');
} catch(err) {
console.error(err.message);
process.exit(1);
}
}
module.exports = connectDB;
I really appreciate any ideas or points of views!!
Thank you so much everyone!
Maybe you already did the job, let me point out a thing here in your code:
app.use(express.static('client/build'))
you maybe need to put like this :
const app = express();
const path = require('path');
app.use('/static', express.static(path.join(`${__dirname}/client/build`)));
then just send the file when the server is online:
app.get('/*', (req, res) => {
res.sendFile(path.join(`${__dirname}/client/build/`));
});
If you have .env file. Try adding this NODE_ENV = production in it.

Why am I receiving the error: "Missing script: Start"?

I'm trying to follow a tutorial for starting up my first NodeJS app, but I don't understand why I am getting this error. I'm attempting to connect a MongoDB database with the app, and obviously had to modify my Start.js file in order to do that... but the error says I'm missing that file completely. Here's my Start.js:
require('dotenv').config();
const mongoose = require('mongoose');
mongoose.connect(process.env.DATABASE, { useMongoClient: true });
mongoose.Promise = global.Promise;
mongoose.connection
.on('connected', () => {
console.log(`Mongoose connection open on ${process.env.DATABASE}`);
})
.on('error', (err) => {
console.log(`Connection error: ${err.message}`);
});
const app = require('./app');
const server = app.listen(3000, () => {
console.log(`Express is running on port ${server.address().port}`);
});
I was told to create a .env file to place in the project folder as well, could this have something to do with it? Maybe the address to the database is incorrect? Any assistance would be greatly appreciated.
EDIT: Here's my package.json file
{
"name": "demo-node-app",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"watch": "nodemon ./start.js"
},
"keywords": [],
"author": "",
"license": "ISC",
"dependencies": {
"body-parser": "^1.19.0",
"dotenv": "^8.2.0",
"express": "^4.17.1",
"express-validator": "^6.3.0",
"mongoose": "^5.8.3",
"pug": "^2.0.4"
},
"devDependencies": {
"nodemon": "^2.0.2"
}
}

Resources