I'm not sure what I did, but I broke something. Trying to deploy an API to Heroku. Everything was fine locally but then I guess I did something wrong and now it's all broken. It works when I go just localhost:5000 and displays that page (which just says "hello world") but when I try to access anything with the API parameters eg: localhost:5000/data/2018-10/gen6ou it just sits. No error is shown in the console. In the terminal, where i ran the command: node index.js it displays: str.charAt is not a function but does not break the connection or anything.
index.js
const express = require('express');
const app = express();
const pool = require("./db"); //stores super secret db info
const cors = require("cors");
const PORT = process.env.PORT || 5500;
// middleware
app.use(cors());
app.use(express.json()); // => req.body
app.use(express.static('public')); //index.html, just says 'hello world'
// get the data
app.get("/data/:date/:tier", async (req, res) => {
try {
const { date, tier } = req.params;
const allData = await pool.query(
"SELECT * FROM smogon_usage_stats WHERE date=$1 AND tier=$2",
[date, tier]
);
const results = allData.rows;
const output = { "data": Object.fromEntries(
results.map(
item => [item.pokemon, item]
))
};
res.json(output);
} catch (error) {
console.log(error.message);
};
});
app.listen(PORT, () => {
console.log(`Server running on port ${PORT}.`);
});
package.json
{
"name": "usage_server",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"start": "node index.js"
},
"keywords": [],
"author": "",
"license": "ISC",
"dependencies": {
"cors": "^2.8.5",
"dotenv": "^8.2.0",
"express": "^4.17.1",
"pg": "^8.5.1"
},
"engines": {
"node": "14.16.0",
"npm": "6.14.11"
},
"proxy": "http://localhost:5000"
}
db.js
const { Pool } = require('pg');
require("dotenv").config();
const devConfig = `postgresql://${process.env.PG_USER}:
${process.env.PG_PASSWORD}#${process.env.PG_HOST}:
${process.env.PG_PORT}/${process.env.PG_DATABASE}`;
const proConfig = {
connectionString: process.env.DATABASE_URL
};
const conn = new Pool({
connectionString: process.env.NODE_ENV === "production" ? devConfig : proConfig
});
module.exports = conn;
In production, your database config object is invalid - the connectionString contains another object (the proConfig).
You seem to be looking for either
const devConfig = {
connectionString: `postgresql://${process.env.PG_USER}:${process.env.PG_PASSWORD}#${process.env.PG_HOST}:${process.env.PG_PORT}/${process.env.PG_DATABASE}`
};
const proConfig = {
connectionString: process.env.DATABASE_URL
};
const conn = new Pool(process.env.NODE_ENV === "production" ? devConfig : proConfig);
or
const connectionString = process.env.NODE_ENV === "production"
? process.env.DATABASE_URL
: `postgresql://${process.env.PG_USER}:${process.env.PG_PASSWORD}#${process.env.PG_HOST}:${process.env.PG_PORT}/${process.env.PG_DATABASE}`;
const conn = new Pool({ connectionString });
Related
server.js
const express_l = require('express');
const path_l = require('path');
const app_l = express_l();
const http_l = require('http');
const server_l = http_l.createServer( app_l);
const socketio_l = require('socket.io');
const io_l = socketio_l( server_l);
app_l.use( express_l.static( path_l.join( __dirname, 'public')) );
io_l.on( "connection", argSocket => { console.log('New websocket connection!'); });
var PORT = 3000 || process.env.PORT;
server_l.listen( PORT, ()=>{ console.log(`from express server on port ${PORT}!`) });
main.js
const socket = io_l();
chat.html
...
...
<script src = "/socket.io/socket.io.js"> </script>
<script src = "js/main.js"> </script>
</body>
</html>
package.json
{
"name": "chatcord",
"version": "1.0.0",
"description": "Realtime chat application built with Nodejs",
"main": "server.js",
"scripts": {
"start": "node server",
"dev": "nodemon server"
},
"author": "xyz",
"license": "MIT",
"dependencies": {
"express": "^4.18.1",
"moment": "^2.29.3",
"socket.io": "^4.5.1"
},
"devDependencies": {
"nodemon": "^2.0.16"
}
}
Now, when I refresh http://localhost:3000/ in browser, I don't see the console.log statement from the on function of socket.io.
Where am I going wrong? Please point out.
Your initialization is wrong. You have to create a new instance of the socket io server and then call it. Check the documentation for more.
https://socket.io/get-started/chat#integrating-socketio
const { Server } = require("socket.io");
const io = new Server(server);
io.on('connection', (socket) => {
console.log('a user connected');
});
Hopefully this helps.
this is from socket io documentation
https://socket.io/get-started/chat
const express = require('express');
const app = express();
const http = require('http');
const server = http.createServer(app);
const { Server } = require("socket.io");
const io = new Server(server);
io.on("connection", async (socket) => {
console.log("someone connected to socket")
//add listener here
socket.on("chat",(data)=> {
console.log(data)
})
});
httpServer.listen(port, host, () => {
console.log(`Server running on http://${host}:${port}`);
});
also this is the emit cheatsheet maybe useful for you
https://socket.io/docs/v3/emit-cheatsheet/
You're consoling on nodejs server so check your terminal for the output of the console.
You need to research how emitting events works in socket (helping material)
I am making a registration form with the MERN stack, I am connecting Express app to mongoDB but I am getting error in connection.
I am following Thapa Technical video on YouTube, and I have done exactly what Thapa did, I don't know what is wrong in this, I am a beginner please help me.
app.js file:
const express = require('express');
const app = express();
require("./db/conn")
const port = process.env.PORT || 3000;
app.get("/", (req, res) => {
res.send("Welcome to Abdullah's webbsite")
});
app.listen(port, () => {
console.log(`Server is running at port no ${port}`)
})
conn.js file:
const mongoose = require("mongoose");
mongoose.connect("mongodb://localhost:27017/userRegistration", {
useNewUrlParser:true,
useUnifiedTopology:true,
useCreateIndex:true
}).then(() =>{
console.log(`Connection Successful`);
}).catch((e) => {
console.log(e);
})
package.json file:
{
"name": "registration-form",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"dev" : "nodemon src/app.js"
},
"author": "Abdullah",
"license": "ISC",
"dependencies": {
"express": "^4.17.3",
"hbs": "^4.2.0",
"mongoose": "^6.2.2"
}
}
console:
Server is running at port no 3000
MongoParseError: option usecreateindex is not supported
at parseOptions (C:\Users\ABDULLAH\Desktop\Registration Form\Registration form\node_modules\mongodb\lib\connection_string.js:289:15)
at new MongoClient (C:\Users\ABDULLAH\Desktop\Registration Form\Registration form\node_modules\mongodb\lib\mongo_client.js:62:63)
at C:\Users\ABDULLAH\Desktop\Registration Form\Registration form\node_modules\mongoose\lib\connection.js:784:16
at new Promise (<anonymous>)
at NativeConnection.Connection.openUri (C:\Users\ABDULLAH\Desktop\Registration Form\Registration form\node_modules\mongoose\lib\connection.js:781:19)
at C:\Users\ABDULLAH\Desktop\Registration Form\Registration form\node_modules\mongoose\lib\index.js:340:10
at C:\Users\ABDULLAH\Desktop\Registration Form\Registration form\node_modules\mongoose\lib\helpers\promiseOrCallback.js:32:5 at new Promise (<anonymous>)
at promiseOrCallback (C:\Users\ABDULLAH\Desktop\Registration Form\Registration form\node_modules\mongoose\lib\helpers\promiseOrCallback.js:31:10)
at Mongoose._promiseOrCallback (C:\Users\ABDULLAH\Desktop\Registration Form\Registration form\node_modules\mongoose\lib\index.js:1140:10)
Please remove useCreateIndex option in connn.js:
mongoose.connect("mongodb://localhost:27017/userRegistration", {
useNewUrlParser:true,
useUnifiedTopology:true
}).then(() =>{
console.log(`Connection Successful`);
}).catch((e) => {
console.log(e);
})
const express = require('express');
const mongoose = require('mongoose');
const app = express();
app.use(express.json());
let userModel;
// configure mongoose
mongoose.connect('mongodb://localhost:27017/userRegistration', (err) => {
if (err) {
console.log(`Error connecting to mongodb => `, err);
} else {
console.log(`Mongodb Connected successfully`);
}
});
I am creating an express app with basic MVC functionality using Sequelize.
Right now I am implementing a route to insert one row of student data into the database. When the server starts, sequelize force sync tables and everything looks fine. I can confirm that the DB exists and Sequelize just created the Students table in it.
Then I insert manually one row using the CL.
mysql> insert into students values(1,'Alan','Johnson');
Now:
the server is listening,
the database was created,
Sequelize was able to see the modules and then create the corresponding table.
The table contains one row which was seeded manually.
My problem is this:
I have a feeling that the connection.js is not finding the .env file.
But, how it that possible if sequelize.sync was able to create a table in the db? Can you please help me find what is wrong in:
http://localhost:3001/api/insertStudent
http://localhost:3001/api/Allstudents
NOTE:
I am using that route just to get to the Student.create() and Student.findAll() command.
app.js
const express = require('express');
const sequelize = require('./config/connection');
const path = require('path');
const router = require('./routes/index');
const PORT = process.env.PORT || 3001;
const app = express();
app.use(express.json());
app.use(router);
sequelize.sync({force: true}).then(
app.listen(PORT, () => {
console.log('Sever running on port: %j', PORT);
console.log('http://localhost:%j/', PORT);
console.log('http://localhost:%j/api/', PORT);
console.log('http://localhost:%j/api/Allstudents', PORT);
console.log('http://localhost:%j/api/insertStudent', PORT);
})
);
package.json
{
"name": "Project-2-connection-test",
"version": "1.0.0",
"description": "",
"main": "app.js",
"dependencies": {
"dotenv": "^10.0.0",
"express": "^4.17.1",
"find-config": "^1.0.0",
"mysql2": "^2.3.0",
"sequelize": "^6.6.5",
"sequelize-cli": "^6.2.0"
},
"devDependencies": {},
"scripts": {
"start": "node app.js"
},
"keywords": [],
"author": "",
"license": "ISC"
}
.env
DB_NAME="student_behavior_db"
DB_USER="root"
DB_PASSWORD=
routes/index.js
const router = require('express').Router();
const student_routes = require('./myApi/studentRoutes');
router.use('/api',student_routes);
router.get('/',(req,res)=>{
res.status(200).send('<h1>Home root</h1>');
})
module.exports = router;
routes/Myapi/index.js
const router = require('express').Router();
const {Student} = require('../../models/index');
/* ----------------------------------------------------------------------NOT WORKING */
router.get('/allStudents', (req, res) => {
try {
const students = Student.findAll();
console.log("---> students :" + JSON.stringify(students));
return res.status(200).json(students);
} catch (e) {
return res.status(500).send(e.message);
}
});
/* ----------------------------------------------------------------------NOT WORKING */
router.get('/insertStudent', (req, res) => {
console.log("---> insertStudent :" );
const studentInsert = Student.create({id:2,firstName:"John",lastName:"Stevens"})
console.log("---> studentInsert :" + studentInsert );
res.status(200).json(studentInsert);
})
router.get('/', (req, res) => {
res.status(200).send('<h1>Root on student-routes</h1>');
})
module.exports = router;
models/student.js
const {Model, DataTypes} = require('sequelize');
const sequelize = require('../config/connection');
class Student extends Model {
/**
* Helper method for defining associations.
* This method is not a part of Sequelize lifecycle.
* The `models/index` file will call this method automatically.
*/
static associate(models) {
// define association here
}
};
Student.init({
id: {type: DataTypes.INTEGER, primaryKey: true},
firstName: {type: DataTypes.STRING, allowNull: false},
lastName: {type: DataTypes.STRING, allowNull: false}
}, {
sequelize,
timestamps: false,
modelName: 'Student',
});
module.exports = Student;
models/index.js
const Student = require('./Student');
module.exports = {Student};
db/schema.sql
DROP DATABASE IF EXISTS student_behavior_db;
CREATE DATABASE student_behavior_db;
config/connections.js
const Sequelize = require('sequelize');
require('dotenv').config();
const sequelize = new Sequelize(
process.env.DB_NAME,
process.env.DB_USER,
process.env.DB_PASSWORD,
{
host: 'localhost',
dialect: 'mysql',
port: 3306,
}
);
module.exports = sequelize;
config/config.json
{
"development": {
"host": "127.0.0.1",
"dialect": "mysql",
"port": 3306
},
"test": {
"host": "127.0.0.1",
"dialect": "mysql",
"port": 3306
},
"production": {
"host": "127.0.0.1",
"dialect": "mysql",
"port": 3306
}
}
Your support is greatly appreciated.
The findAll returns a promise and you're not resolving that promise.
https://sequelize.org/master/class/lib/model.js~Model.html#static-method-findAll
Either invoke .then on Student.findAll() or use async/await on your middleware.
I want to upload file from postman to node js but I have problem.
POSTMAN
Write url,check post method,check form-data,check file,write file name and choose file
This is my code
app.js
const express = require('express');
const bodyParser = require('body-parser');
const fileUpload = require('express-fileupload');
app.use(fileUpload());
app.use(bodyParser.urlencoded({extended: false}));
app.use(bodyParser.json());
router.js
router.post('/schedule/entry', function(req,res){
console.log(req.file.name);
});
Console return me undefined name, if I write this code
router.post('/schedule/entry', function(req,res){
console.log(req.file);
});
Return 'undefined'
Why?
package.json
{
"name": "nodejs-rest-api-authentication",
"version": "1.0.0",
"description": "",
"main": "app.js",
"scripts": {
"start": "node server.js",
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "",
"license": "ISC",
"dependencies": {
"bcryptjs": "^2.4.3",
"body-parser": "^1.16.1",
"csv-array": "0.0.22",
"csv-write-stream": "^2.0.0",
"express": "^4.14.1",
"express-fileupload": "^0.3.0",
"fast-csv": "^2.4.1",
"formidable": "^1.1.1",
"json2csv": "^3.11.5",
"jsonwebtoken": "^8.1.0",
"mysql": "^2.15.0"
}
}
server.js
const app = require('./app');
const port = process.env.PORT || 3000;
const server = app.listen(port, function() {
console.log('Server listening on port ' + port);
});
screenshots
screenshots
codeGit
Based on the discussion in the comment section:
const express = require('express')
const app = express()
const formidable = require('formidable')
const path = require('path')
const uploadDir = '' // uploading the file to the same path as app.js
app.post('/', (req, res) =>{
var form = new formidable.IncomingForm()
form.multiples = true
form.keepExtensions = true
form.uploadDir = uploadDir
form.parse(req, (err, fields, files) => {
if (err) return res.status(500).json({ error: err })
res.status(200).json({ uploaded: true })
})
form.on('fileBegin', function (name, file) {
const [fileName, fileExt] = file.name.split('.')
file.path = path.join(uploadDir, `${fileName}_${new Date().getTime()}.${fileExt}`)
})
});
app.listen(3000, () => console.log('Example app listening on port 3000!'))
Attached Screenshots:
Because of body-parser middleware file will be not available in req so you must use another middleware libraries like connect-busboy or multer or connect-multiparty
I'm using a nodejs backend (following this tutorial to pull in tweets into the front end of my application.
Now that I'm ready to deploy to a development server, I've packaged the frontend with ng build --prod, and that looks and works fine, except for the module with loading tweets. How do I host the node server part of the application to display the tweets properly?
Here are the files of my node app. It's held in the root of my project folder, outside of src.
server.js
var express = require('express');
var bodyParser = require('body-parser');
var cors = require('cors');
var functions = require('./functions');
var app = express();
app.use(bodyParser.urlencoded({extended: true}));
app.use(cors());
app.post('/authorize', functions.authorize);
app.post('/search', functions.search);
app.listen(3000);
console.log('listening now');
functions.js
var request = require('request');
var config = require('./config');
functions = {
authorize: function(req, res) {
var header = config.consumerkey + ':' +config.consumersecret;
var encheader = new Buffer(header).toString('base64');
var finalheader = 'Basic ' + encheader;
request.post('https://api.twitter.com/oauth2/token', {form: {'grant_type': 'client_credentials'},
headers: {Authorization: finalheader}}, function(error, response, body) {
if(error)
console.log(error);
else {
config.bearertoken = JSON.parse(body).access_token;
res.json({success: true, data:config.bearertoken});
}
})
},
search: function(req, res) {
var searchquery = req.body.query;
var encsearchquery = encodeURIComponent(searchquery);
var bearerheader = 'Bearer ' + config.bearertoken;
request.get('https://api.twitter.com/1.1/search/tweets.json?q=' + encsearchquery +
'&result_type=recent', {headers: {Authorization: bearerheader}}, function(error, body, response) {
if(error)
console.log(error);
else {
res.json({success: true, data:JSON.parse(body.body)});
}
})
}
}
module.exports = functions;
config.js
var appsettings = {
consumerkey: 'key',
consumersecret: 'key',
bearertoken: ''
};
module.exports = appsettings;
package.json
{
"name": "backend",
"version": "1.0.0",
"description": "",
"main": "server.js",
"scripts": {
"start": "node server",
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "brooklynbrim",
"license": "MIT",
"devDependencies": {
"body-parser": "^1.17.2",
"cors": "^2.8.4",
"express": "^4.15.4",
"request": "^2.81.0"
}
}
I would recommend you to host your nodeJS app on Heroku.
You can get started Here.
And for the Angular App, I would recommend you Firebase. Easiest way to host your angular app. How to deploy Angular apps on Firebase