I am new to node js and postman and was working on this backend project to store a random persons details in my database. This is my app.js file:
var express=require("express");
var app=express();
//database
var mongoose=require("mongoose");
//connecting to database
mongoose.connect("mongodb+srv://mymongohost?retryWrites=true&w=majority",{ useNewUrlParser: true, useUnifiedTopology: true });
//creating user schema
var userSchema=new mongoose.Schema({
name:String,
age: String,
gender: String,
number: String,
location: String
});
var User =mongoose.model("user",userSchema);
//using body parser
var bodyParser=require("body-parser");
app.use(bodyParser.urlencoded({extended:true}));
//Creating a user
/*User.create({
name: "Snehan",
age: "30",
gender: "male",
number: "998899876",
location: "Sample address, near Thane, Mumbai,Mahasrashtra"
})*/
//ROUTES
app.get("/",function(req,res){
res.redirect("/user");
})
//sending all user data
app.get("/user", function(req,res){
User.find({}, function(err,user)
{
if(err)
res.send(err);
else
res.json(user);
})
})
//creating new user data
app.post("/user",function(req,res){
//storing the data received from body
var name=req.body.name;
var age=req.body.age;
var gender=req.body.gender;
var number=req.body.number;
var location=req.body.location;
//creating new object with all details
var newUser={
name:name,
age:age,
gender:gender,
number:number,
location: location
}
User.create(newUser,function(err,newlyCreatedUser){
if(err)
{res.send("Unable to create new user");}
else
{res.send(newlyCreatedUser);}
});
})
app.listen(process.env.PORT || 3000, function() {
console.log("Server started on port 3000");
});
Package.json:
{
"name": "userdetails",
"version": "1.0.0",
"description": "",
"main": "app.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "",
"license": "ISC",
"dependencies": {
"body-parser": "^1.19.0",
"express": "^4.17.1",
"mongoose": "^5.10.0"
}
}
However whenever im trying to test my code using postman,im unable to add a post a users data.
This was the post request I had sent. But the newlyCreated User object looks like:
{
"_id": "5f37ba449adfe112529f872a",
"__v": 0
}
Could anyone help me abt where im going wrong?
Your app is missing a json body-parser middleware, hence req.body is empty. Add the following line to your app-setup:
app.use(bodyParser.urlencoded({extended: true}));
app.use(bodyParser.json());
Your code is missing this:
app.use(bodyParser.json())
Related
Making a GET request to my own authenticating user users/{id}/tweets in nodeJS and using V2 Twitter api, returns only tweets posted by my own authenticating user id.
What I need?
To GET all tweets both posted by myself and the ones that are showing in my timeline from users I follow.
Basically, the same result as in Twitter V1 GET statuses/home_timeline
How can I get this in V2?
index.js
const express = require("express");
const app = express();
app.use(express.urlencoded({ extended: true })); // for parsing application/x-www-form-urlencoded
app.use(express.json()); // for parsing application/json
const Twit = require("twitter-lite");
const config = require("./config");
const client = new Twit(config.appConfig);
function getTimeLineTweetsInV2() {
return new Promise(async (resolve, reject) => {
try {
let result = await client.get("users/tweets/1497521946694717448");
resolve(result);
} catch (error) {
console.log("errorrrrrrrrrr is", error);
reject(error);
}
});
}
(async function BotMain() {
let tweetsReceived = await getTimeLineTweetsInV2();
console.log(tweetsReceived);
})();
app.listen(3000, () => {
console.log("listeing on port 3000");
});
config.js
const dotenv = require("dotenv");
const path = require("path");
const ENV_FILE = path.join(__dirname, ".env");
dotenv.config({ path: ENV_FILE });
const appConfig = {
//define subdomain of twitter api URL e.g. api.twitter.com, streams.twitter.com
version: "2",
extension: false,
consumer_key: process.env.apikey,
consumer_secret: process.env.apisecret,
access_token_key: process.env.accesstoken,
access_token_secret: process.env.accesstokensecret,
};
module.exports = {
appConfig,
};
package.json
{
"name": "twitter_app",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "",
"license": "ISC",
"dependencies": {
"dotenv": "^16.0.0",
"express": "^4.17.3",
"path": "^0.12.7",
"twitter-lite": "^1.1.0"
}
}
There is no equivalent to the home timeline API in v2 - yet. This is on the roadmap. You’ll need to use the v1.1 API, or, be patient until a new version is available.
the app displays and behaves perfectly on localhost but does not display at all once deployed on CPanel. I have deployed it on CPanel and run the command npm install from the GUI and I have run it also from the terminal using 'npm install -g npm-check-updates' followed by 'ncu -u'
I have tried to deploy the app the same way once more in case I made a mistake and get the same result. I don't understand why it does not seem to find 'app.get("/"'
app.js
var app = express();
var mysql = require("mysql"); // allow access to sql
var bodyParser = require("body-parser");
const path = require("path");
const VIEWS = path.join(__dirname, "views");
app.use(express.static("scripts"));
app.use(express.static("images"));
let index = 0;
var session = require("express-session");
var globalGallery = [];
let filter = false;
var lastSearchItem = "";
//var MySQLStore = require('express-mysql-session')(session);
app.use(
bodyParser.urlencoded({
extended: true,
})
);
app.set("view engine", "pug");
const db = mysql.createConnection({
host: "-------",
user: "------",
password: "--------",
database: "--------",
port: 3306,
});
db.connect((err) => {
if (err) {
throw err;
} else {
console.log("db connected!");
}
});
app.get("/", function (req, res) {
let sql = "select * FROM photo ORDER BY photoId DESC; ";
let query = db.query(sql, (err, gallery) => {
if (err) throw err;
globalGallery = gallery;
filter = false;
res.render("index", {
gallery: globalGallery,
});
});
});
index.pug
extends layout
block content
.maincontent
form(method="post" action="/filterphotos")
input.search(name="search", type="text", Placeholder="type 'ir' for example...")
button.searchbutton(type="submit") Search
.grid-container
each photo in gallery
- var text
- text = photo.photoPlace? photo.photoPlace : text
- text = photo.photoCountry? text+" "+photo.photoCountry : text
- text = photo.photoComments? text+" "+photo.photoComments : text
a.div.tooltip(href='/displayphoto/'+photo.photoId)
img.photothumbnail(src="http://isabellebidou.com/images/"+photo.photoThumbnail, alt=photo.photoThumbnail)
if text.length > 1
span.tooltiptext #{text}
package.json
{
"name": "isabellebidou.photos",
"version": "1.0.0",
"description": "photo website",
"main": "app.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"repository": {
"type": "git",
"url": "photoapp"
},
"author": "",
"license": "ISC",
"dependencies": {
"body-parser": "^1.19.0",
"constantinople": "^4.0.1",
"express": "^4.17.1",
"express-session": "^1.17.1",
"jade": "^1.11.0",
"mysql": "^2.18.1",
"path": "^0.12.7",
"pug": "^3.0.0"
}
}
terminal screenshot
I am currently building a simple CRUD app using ExpressJS, and host it on Heroku using free account.
The problem I ran into is:
GET API for getting all items works on localhost, but show status 503 when hosting on Heroku;
POST API for updating one item works on localhost, but same issue as GET API above;
All 503 errors are after 30s of loading, this should be a setting from Heroku.
I do have other API end points that work on both local and Heroku server:
GET API for getting one item using ID
My guessing:
The issue should not be a code issue
There is some issue when the code is deployed and Heroku cannot process this request
I tried to find some articles on the web but this seems hard to diagnose, anyone who has experience please let me know how I can solve this issue. Appreciate your comments.
My Mongoose Schema
const mongoose = require("mongoose");
const ThoughtSchema = mongoose.Schema({
title: {
type: String,
required: true
},
content: {
type: String,
required: true
},
date: {
type: Date,
default: Date.now
}
});
module.exports = mongoose.model("Thought", ThoughtSchema);
2 end points that do not work
// Returns all thoughts
router.get("/", async (req, res) => {
try {
const thought = await Thought.find();
res.json(thought);
} catch (err) {
res.json({ message: err });
}
});
// Submit a post
router.post("/", async (req, res) => {
const thought = new Thought({
title: req.body.title,
content: req.body.content
});
try {
const savedThought = await thought.save();
res.json(savedThought);
} catch (err) {
res.json({ message: err });
}
});
The end point that works
// Specific thought
router.get("/:thoughtId", async (req, res) => {
try {
const thought = await Thought.findById(req.params.thoughtId);
res.json(thought);
} catch (err) {
res.json({ message: err });
}
});
My package.json for this express app
{
"name": "my-thoughts-app",
"version": "0.1.0",
"description": "An app to records user's thoughts",
"main": "index.js",
"scripts": {
"start": "node index.js",
"test": "echo \"Error: no test specified\" && exit 1"
},
"repository": {
"type": "git",
"url": "git+https://github.com/PayneTang/my-thoughts-app.git"
},
"author": "Payne Tang",
"license": "ISC",
"bugs": {
"url": "https://github.com/PayneTang/my-thoughts-app/issues"
},
"homepage": "https://github.com/PayneTang/my-thoughts-app#readme",
"dependencies": {
"dotenv": "^8.2.0",
"express": "^4.17.1",
"mongoose": "^5.8.11"
},
"devDependencies": {
"typescript": "^3.7.5"
}
}
EDIT:
My index.js
const express = require("express");
const path = require("path");
const app = express();
const mongoose = require("mongoose");
const thoughtRoute = require("./routes/thought");
require("dotenv").config();
console.log(process.env);
// Mongoose settings
mongoose.connect(
process.env.DB_CONNECTION,
{ useNewUrlParser: true, useUnifiedTopology: true },
() => {
console.log("Connected to DB!");
}
);
app.use(express.json());
app.use((req, res, next) => {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Methods", "*");
res.header(
"Access-Control-Allow-Headers",
"Origin, X-Requested-With, Content-Type, Accept"
);
next();
});
app.use("/api/thought", thoughtRoute);
app.get("/api/test", (req, res) => {
res.send("hi");
});
// Serve client side
app.use(express.static(path.join(__dirname, "client/build")));
app.use(express.static(path.join(__dirname, "client/public")));
// app.get("*", (req, res) => {
// res.sendFile(path.join(__dirname, "client/build/index.html"));
// });
const PORT = process.env.PORT || 5000;
app.listen(PORT, () => {
console.log("Listening on port " + PORT + "...");
});
The root cause after checking is due to the access restriction from Heroku to Mongo atlas.
After adding 0.0.0.0/0 for IP whitelist, I am able to get data from MongoDB.
Reference: https://docs.atlas.mongodb.com/security-whitelist/#add-whitelist-entries
I had the same problem and I was able to fix it by doing these two steps:
Add node version to package.json file:
"engines": {
"node": "14.17.3"
}
}
I changed access settings in MongoDB, allowing access to the database from anywhere (basically, whitelisting 0.0.0.0/0 IP address)
In my case, the issue was in package.json I installed two new packages yesterday and in my package.json:
"engines": {
"node": "12.16.0"
},
I changed the version to the my current system version:
"engines": {
"node": "14.5.0"
},
this is how my 503 service unavailable error gone.
This can be caused in several ways to the Node app.
1- Make sure that you specify the right port as what heroku does is it runs our app on a dynamic port.
const PORT = process.env.PORT || 3000;
app.listen(PORT, err => {
if(err) throw err;
console.log("%c Server running", "color: green");
});
as described in this comment
https://stackoverflow.com/a/52992592/11887902
2- Make sure that you added the Procfile with
npm start
to start the application.
3- If you are using Nodemon and you install it globally, just make sure that you install it locally too.
Finally, just have a look at the logs of the project to figure what heppen to make your project not in the service.
These cases happened to me and caused this error.
My issue was caused due to case sensitivity that is at times ignored by node,
in my controllers I had a file named sessions.js yet when importing in my routes I had mistakenly put ... = require('../controllers/Sessions'),
Nodemon was running without issues as I was developing but upon deploying on heroku it crashed so I changed to ... = require('../controllers/sessions')
and now it runs ok
I'm new to APIs based on nodeJS and I would like to connect to an already existing collection in a MongoDB database.
If I try to access http://localhost:8080/teams I get an error on the browser: Cannot GET /Teams.
Not even the console.log get printed but nodemon (that I'm using to load after each save) shows no errors.
This is an example of the existing records:
use MYDB
db.TeamsCol.find()
{ "_id" : ObjectId("5d702df59ba60607dad06df4"), "teamID" : 1, "teamName" : "PT", "datetime" : "04-09-2019 10:21:16 Wednesday" }
{ "_id" : ObjectId("5d702ed59ba60607dad06df5"), "teamID" : 2, "teamName" : "ES", "datetime" : "01-09-2019 11:20:00 Sunday" }
I built the following struture:
project folder: API
API/server.js
API/models/teamModel.js
API/Routes/teamRouter.js
as described below:
API/server.js file:
// Import express
let express = require('express');
// Import Body parser
let bodyParser = require('body-parser');
// Import Mongoose
let mongoose = require('mongoose');
// Initialise the app
let app = express();
// Setup server port
var port = process.env.PORT || 8080;
// Import routes
let apiRouter = require("./Routes/teamRouter");
// Connecting to the database
const db = mongoose.connect('mongodb://localhost/MYDB', {useNewUrlParser: true});
// setting body parser middleware
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
// API routes
app.use('/Teams', apiRouter);
// Running the server
app.listen(port, () => {
console.log(`http://localhost:${port}`)
})
API/models/teamModel.js file:
// Import Mongoose
let mongoose = require('mongoose');
const Schema = mongoose.Schema;
const teamModel = new Schema({
teamID: { type: Number },
teamName: { type: String },
datetime: { type: String },
})
module.exports = mongoose.model('teamsModel', teamModel, 'TeamsCol');
API/Routes/teamRouter.js file:
// Import express
let express = require('express');
// Import Teams controller
var Team = require('../models/teamModel');
const teamRouter = express.Router();
teamRouter.route('/teams')
.get((req, res) => {
Console.log(req)
Team.find({}, (err, teams) => {
res.json(teams)
})
})
// Middleware
teamRouter.use('/:team', (req, res, next)=>{
Team.findById( req.params.team, (err,team)=>{
if(err)
res.status(500).send(err)
else {
req.team = team;
next()
}
})
})
teamRouter.route('/:team')
.get((req, res) => {
res.json(req.team)
}) // end get Teams/:team
// Export API routes
module.exports = teamRouter;
Here are the versions I'm using
mongo --version
MongoDB shell version v3.6.3
node --version
v8.9.4
and also the package.json contents:
{
"name": "teamsapi",
"version": "1.0.0",
"description": "",
"main": "server.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "",
"license": "ISC",
"dependencies": {
"body-parser": "^1.19.0",
"express": "^4.17.1",
"mongoose": "^5.6.12"
}
}
Any ideas?
Because in your server.js file, you already used:
app.use('/Teams', apiRouter);
So the api /teams doesn't exist, it should be /Teams/teams. And the full url will be http://localhost:8080/Teams/teams.
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