node server.js return nothing - node.js

I'm very new to Node. I just installed it via Brew and when I ran node server.js in the Terminal, the Terminal does nothing for hours.
node -v
v6.6.0
This is the server file, it is from a tutorial video that I'm watching. The point of this simple express server is to allow me the ability to quickly serve test data via HTTP to the front-end.
package.json :
{
"name": "simple-server",
"version": "1.0.0",
"description": "",
"main": "server.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"start": "node server.js"
},
"author": "",
"license": "ISC",
"dependencies": {
"body-parser": "^1.14.1",
"express": "^4.13.3",
"path": "^0.12.7"
}
}
server.js file :
var express = require('express');
var path = require('path');
var bodyParser = require('body-parser');
var app = express();
//Allow all requests from all domains & localhost
app.all('/*', function(req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "X-Requested-With, Content-Type, Accept");
res.header("Access-Control-Allow-Methods", "POST, GET");
next();
});
app.use(express.static(path.join(__dirname + '/public')));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: false}));
var persons = [
"person1.jpg",
"person2.jpg",
"person3.jpg",
"person4.jpg",
"person5.jpg",
"person6.png"
];
app.get('/persons', function(req, res) {
console.log("GET From SERVER");
res.send(persons);
});
app.listen(6069);
Thanks in advance

Try adding a console.log("started!") before app.listen. I'm guessing the server starts, but as is seen in your code, the only log it does is when it receives a request.
Try accessing http://localhost:6069/persons in your browser.
Edit: this defines a server response
app.get('/persons', function(req, res) {
console.log("GET From SERVER");
res.send(persons); <-- server sends persons array to client
});

Related

Node.js not responding to API calls with my app? Working perfectly during development environment, however not when hosted

Trying to make my first Vue application, simple game with MEVN stack. Working perfect interacting with backend on development environment, however when hosting it doesn't fetch the data from the server.
Anyone able to point out what I have incorrect with the below?
More info below:
File structure:
/root
 |- config.js
 |- server.js
 |- package.json + package-lock.json
 |- client/
  |- vue.config.json
  |- ... (rest of dist, src, node_modules, public etc.)
 |- models/
  |- Elf.js + HighScore.js
 |- routes/
  |- api/
   |- elf.js + highScore.js
config.js
module.exports = {
hostUrl: process.env.HOST_URL,
mongoURI: process.env.MONGO_URI,
PORT: process.env.PORT || 3000,
};
server.js
const express = require("express");
const app = express();
const port = 3000;
const mongoose = require("mongoose");
const { PORT, mongoURI } = require("./config.js");
// routes
const Player = require("./routes/api/player");
const Elf = require("./routes/api/elf");
const HighScore = require("./routes/api/highScore");
// cors is a middleware that allows us to make requests from our frontend to our backend
const cors = require("cors");
// morgan is a middleware that logs all requests to the console
const morgan = require("morgan");
// body-parser is a middleware that allows us to access the body of a request
const bodyParser = require("body-parser");
const path = require("path");
app.use(cors());
// use tiny to log only the request method and the status code
app.use(morgan("tiny"));
app.use(bodyParser.json());
// chek if we are in production
if (process.env.NODE_ENV === "production") {
// check if we are in production mode
app.use(express.static("client/dist"));
app.get("*", (req, res) => {
res.sendFile(path.resolve(__dirname, "client", "dist", "index.html"));
});
}
// test if server is running and connected to mongoDB
app.get("/", (req, res) => {
res.send("Hello World!");
});
// app.get("/", (req, res) => {
// res.send("Hello World!");
// });
// use routes
app.use("/api/", Player);
app.use("/api/", Elf);
app.use("/api/", HighScore);
mongoose
.connect(mongoURI, {
useNewUrlParser: true,
useUnifiedTopology: true,
useUnifiedTopology: true,
})
.then(() => console.log("MongoDB connected..."))
.then(() => {
// log uri to console
console.log(`MongoDB connected to ${mongoURI}`);
})
.catch((err) => console.log(err));
app.listen(PORT, () => {
console.log(`Example app listening at ${PORT}`);
});
package.json
{
"name": "week1",
"version": "1.0.0",
"description": "",
"main": "server.js",
"scripts": {
"server": "nodemon server.js --ignore 'client/'",
"client": "npm run serve --prefix client",
"dev": "concurrently \"npm run server\" \"npm run client\"",
"start": "node server.js",
"build": "npm install --prefix client && npm run build --prefix client"
},
"keywords": [],
"author": "",
"license": "ISC",
"dependencies": {
"body-parser": "^1.20.1",
"bootstrap": "^5.2.3",
"cors": "^2.8.5",
"dotenv": "^16.0.3",
"express": "^4.18.2",
"mongoose": "^6.7.5",
"morgan": "^1.10.0",
"portal-vue": "^2.1.7"
},
"devDependencies": {
"concurrently": "^7.6.0",
"nodemon": "^2.0.20"
}
}
Running within my dev environment at root dir using 'npm run dev', the app works flawlessly send/ receive data from mongoDB during this time. This starts up http://localhost:8080/. Also tried install of 'npm install -g serve' and running 'serve -s dist', this starts up serving at localhost:36797 and working flawlessly too.
I have tried to setup on Vercel & Render, both giving me the same issue where I'm not getting much feedback and the data isn't being fetched. Anyone else has this issue before?

Heroku Deployment not working with MongoDb

I created one demo app with ReactJS, NodeJS, MongoDb and Express. Trying to deploy on heroku. It works fine, if i dont use mongo, but as soon as i introduced mongo db. I am getting error cannot GET /.
I am using mongodb atlas. Do I need heroku addon to use database?
server.js
// Import dependencies
const express = require('express');
const bodyParser = require('body-parser');
const cors = require('cors');
const path = require('path');
const MongoClient = require("mongodb").MongoClient;
const ObjectId = require("mongodb").ObjectID;
const mongodb = require('mongodb');
const fs = require('fs');
const moment = require("moment");
require('dotenv').config();
const CONNECTION_URL = process.env.MONGODB_URI || "mongodb+srv://<username>:<password>#cluster0.xzzno.mongodb.net/<dbname>?retryWrites=true&w=majority";
const DATABASE_NAME = "DBNAME";
const port = process.env.PORT || 5000;
const app = express();
// Set our backend port to be either an environment variable or port 5000
// This application level middleware prints incoming requests to the servers console, useful to see incoming requests
app.use((req, res, next) => {
console.log(`Request_Endpoint: ${req.method} ${req.url}`);
next();
});
// Configure the bodyParser middleware
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
extended: true
}));
// Configure the CORs middleware
app.use(cors());
app.get("/test/", (request, response) => {
response.send({"name":"Hello Test!!!"});
});
var database, userSignUp;
app.listen(port, () => {
MongoClient.connect(CONNECTION_URL, { useNewUrlParser: true }, (error, client) => {
if(error) {
throw error;
}
database = client.db(DATABASE_NAME);
userSignUp = database.collection("UserData");
console.log("Connected to `" + DATABASE_NAME + "`!");
});
})
package.json
{
"name": "testproject",
"version": "1.0.0",
"description": "Learning Deployment",
"main": "server.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"client": "cd client && npm start",
"server": "nodemon server.js",
"dev": "concurrently --kill-others-on-fail \"npm run client\" \"npm run server\"",
"client:build": "cd client && npm run build"
},
"repository": {
"type": "git",
"url": "git+https://github.com/Username/TestProject.git"
},
"author": "Ankita Jaiswal",
"license": "ISC",
"bugs": {
"url": "https://github.com/Username/TestProject/issues"
},
"homepage": "https://github.com/Username/TestProject#readme",
"dependencies": {
"body-parser": "^1.19.0",
"concurrently": "^5.3.0",
"cors": "^2.8.5",
"dotenv": "^8.2.0",
"express": "^4.17.1",
"nodemon": "^2.0.7",
"moment": "^2.29.1",
"mongodb": "^3.6.3",
"mongoose": "^5.11.8"
}
}
procfile
web: npm run dev
have tried web: npm start as well.
Just from my limited experience, I've had the same issue and it turned out I forgot to configure my environment variables on Heroku, so my MONGO_URI was undefined. If not that, you can use the Heroku CLI and run heroku logs --tail from the root of your project and might be able to see more about what's going on.
const CONNECTION_URL = process.env.MONGODB_URI || "mongodb+srv://<username>:<password>#cluster0.xzzno.mongodb.net/<dbname>?retryWrites=true&w=majority";
The upper code is incorrect. You have to change < username > and < password > (both include < >) by your usename and your password! Example:
const CONNECTION_URL = process.env.MONGODB_URI || "mongodb+srv://kanechan25:kane02052409#cluster0.xzzno.mongodb.net/<dbname>?retryWrites=true&w=majority";

Failed at the app#1.0.0 start script This is probably not a problem with npm. There is likely additional logging output above

Hi Guys, I have created a little project of Mern stack. I am deploying it correctly on Heroku. But as soon as I am checking her on Heroku after deploying, then Failed to load resource: the server responded with a status of 503 (Service Unavailable) error is coming.
But as soon as I run heroku local in cmd after deploying then it is working correctly. I am giving below the heroku setup code. Please guide me. please ........
package.sjon file of backend
{
"name": "app",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"start": "npm install && node index",
"heroku-postbuild": "NPM_CONFIG_PRODUCTION=false npm install --prefix client && npm run build --prefix client"
},
"dependencies": {
"config": "^3.3.1",
"express": "~4.16.1",
"express-fileupload": "^1.1.7-alpha.3",
"mongoose": "^5.9.12",
"nodemailer": "^6.4.6"
},
"keywords": [],
"author": "",
"license": "ISC"
}
Index.js file of backend
var express = require('express');
var path = require('path');
const connectDB = require('./config/db')
var indexRouter = require('./routes/index');
var usersRouter = require('./routes/users');
var studentRouter = require('./routes/student')
var app = express();
connectDB();
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(express.static(path.join(__dirname, 'public')));
app.use(express.static('client/build'))
app.get('/', (req, res) => {
res.sendFile(path.resolve(__dirname, 'client', 'build', 'index.html'))
})
app.use('/', indexRouter);
app.use('/', studentRouter);
app.use('/users', usersRouter);
if (process.env.NODE_ENV == "production") {
app.use(express.static('client/build'))
app.get('*', (req, res) => {
res.sendFile(path.resolve(__dirname, 'client', 'build', 'index.html'))
})
}
var port = process.env.PORT || '8000';
app.listen(port, () => {
console.log(`server run port ${port}`);
})
module.exports = app;
All these codes are absolutely correct. I had a problem creating a cluster in mongodb atlas. The problem was that I had selected add current ip address while creating the cluster. Whereas I had to select allow from anywhere. So now I have selected the book. And now it is doing the right thing.
In my case, changing network access form anywhere in my MongoDB cluster, fixed the problem.
Also, don't forget to hit restart all dynos.

Deploy SQL Server api with Express.js to Heroku

I'm very new with Express.js, but right now i've created an api of SQL Server DB. It works fine on localhost, but now, i've deployed on Heroku. While my CMD prompt is open, my api works fine, but when it's close, i get an Internal Server Error.
Previously, i've created a test using Mongo as DB, mongoose and deployed to Heroku an the api still working even when the prompt isn't open. Someone knows if i have to create another .js document just like in mongoose or else to keep working my api?
This is my code on the .js document (server.js):
const express = require('express');
const bodyParser = require('body-parser');
const sql = require('mssql');
const app = express();
app.use(bodyParser.json());
app.use(function (req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Methods", "GET,HEAD,OPTIONS,POST,PUT");
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, contentType,Content-Type, Accept, Authorization");
next();
});
const dbConfig = {
user: "daUser",
password: "daPass",
server: "daServer",
database: "DaDB"
}
const executeQuery = function (res, query) {
sql.connect(dbConfig, function (err) {
if (err) {
console.log(err);
res.send(err);
}
else {
// create Request object
var request = new sql.Request();
// query to the database
request.query(query, function (err, result) {
if (err) {
console.log(err);
res.send(err);
}
else {
res.send(result);
}
});
}
});
}
app.get("/api/HolidayBaseApi", function (req, res) {
var query = "SELECT * FROM [HolidaysBase]";
executeQuery(res, query);
})
const PORT = process.env.PORT || 8080
app.listen(PORT, () => {
console.log("App now running on port", PORT);
});
My package.json next:
{
"name": "holidaysbaseapi",
"version": "1.0.0",
"description": "Api of Holidays",
"main": "server.js",
"scripts": {
"start": "node server.js",
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "Chuck Villavicencio",
"license": "ISC",
"dependencies": {
"body-parser": "^1.18.3",
"express": "^4.16.4",
"mssql": "^4.3.0"
},
"engines": {
"node": "8.11.3",
"npm": "5.6.0"
}
}
On Heroku i've installed the Heroku CLI; logged in, Clone the repository and deployed my changes.
I'm using Express.js, Node, SQL Server and Heroku
The problem is that your SQL server db is created on you local machine and heroku can't connect to it. You can you the postgresDB provided by heroku or create the sql server db in any provider around the internet and replace the dbConfig with the configs of that db

Missing Script: Start, Heroku Deployment Error

My Node.js script is unable to be deployed to Heroku and the error comes in the console saying that I'm missing my start script even though I have it.
Package.JSON
{
"name": "kash",
"version": "1.0.0",
"description": "",
"main": "app.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"start": "node app.js"
},
"author": "",
"license": "ISC"
}
App.js
var express = require("express");
var request = require("request");
var bodyParser = require("body-parser");
var app = express();
app.use(bodyParser.urlencoded({extended: false}));
app.use(bodyParser.json());
app.listen((process.env.PORT || 5000));
// Server index page
app.get("/", function (req, res) {
res.send("Deployed!");
});
// Facebook Webhook
// Used for verification
app.get("/webhook", function (req, res) {
if (req.query["hub.verify_token"] === process.env.VERIFICATION.TOKEN) {
console.log("Verified webhook");
res.status(200).send(req.query["hub.challenge"]);
} else {
console.error("Verification failed. The tokens do not match.");
res.sendStatus(403);
}
});
Console Log screenshots:
Screenshot 1
Screenshot 2

Resources