RELATION "customers " does not exist but in fact exits - node.js

im trying to put together a simple website, but when trying to insert to my Heroku database it says my relation (table) does not exist but in fact exists!!..I connect through database_url provided by Heroku and when I connect through my command line and insert new rows, they get added and I can see their table and data but when I try to insert the data everytime I hit summit in the form, the error pops up like there were no table with that name..
const express = require('express');
app = express();
require('dotenv').config()
var sslRedirect = require("heroku-ssl-redirect").default;
var compression = require('compression');
const { Client } = require('pg');
const client = new Client({
connectionString: process.env.DATABASE_URL,
})
//MIDDLEWARE
app.set("port",process.env.PORT || 3000);
app.set("view engine", "ejs");
app.use(sslRedirect());
app.disable('x-powered-by');
app.use(compression());
app.use(express.static("public"));
app.use(express.json());
app.use(
express.urlencoded({
extended:false
})
);
app.use
const errorController = require('./controllers/errorController');
//const middleware = require('./controllers/middleware')
//ROUTES
app.get('/',(req,res,next) => {
res.render('test')
});
app.post('/thanks', async (req, res) => {
data = {
name : req.body.name,
email : req.body.email,
service: req.body.service,
message: req.body.message};
const text ='INSERT INTO customers(name,email,service,message) VALUES($1, 2$, 3$, 4$) RETURNING *;'
const values = [data.name, data.email, data.service, data.message];
client.connect()
try {
const res = await client.query(`INSERT INTO customers (name,email,service,message) VALUES(${data.name},${data.email},${data.service},${data.message}) RETURNING *;`);
console.log(res.row[1])
client.end()
}catch (err) {
console.log(err.stack)
client.end()
}
res.render('thanks')
})
app.get('/contact',(req,res) => {
res.render('contact')
})
app.get("/services" , (req,res) => {
res.render('services')
})
app.get("/about" , (req,res) => {
res.render("about")
})
app.get('/maysspabeauty.com/contact/*' , (req , res) => {
res.render('contact')
})
app.use(errorController.pageNotFoundError);
app.use(errorController.internalServerError)
app.listen(app.get("port"), () => {
console.log(`server running at http://localhost:${app.get("port")}`);
});
here is screenshot of the errorerror image

Solved this.... seems my problem was just that i was using heroku hobby-dynos and they are NOT meant to be used in production....after i upgraded the dynos, it just throw me this error (no pg_hba.conf entry for host) which i fixed just using ssl"{
ssl:
rejectUnauthorized:false
};

Related

couchbase, ottoman throw error when I create a new instance?

I'm new in couchbase and I'm using ottoman framework. I connected the database using ottoman and I create the schema and model User and exported it into controller file. When I create a new instance for that model, ottoman throw an error TypeError: User is not a constructor.
I search so many time and I red the official and non official documents and test it severely. I wrote all about the db in separate file and no change. I'll attach the file below it . But I didn't get any solution. please let me know...
const ottoman = require("ottoman");
exports.connect = async () => {
try {
await ottoman.connect({
connectionString: process.env.DB_CONNECTION_STRING,
bucketName: process.env.DB_BUCKET,
username: process.env.DB_USERNAME,
password: process.env.DB_PASSWORD,
});
console.log("Database connected.");
await ottoman.start();
} catch (error) {
console.log("Database not connected due to: ", error.message);
}
};
connect();
const User = ottoman.model("User", {
firstName: String,
lastName: String,
email: String,
tagline: String,
});
const perry = new User({
firstName: "Perry",
lastName: "Mason",
email: "perry.mason#example.com",
tagLine: "Who can we get on the case?",
});
const tom = new User({
firstName: "Major",
lastName: "Tom",
email: "major.tom#example.com",
tagLine: "Send me up a drink",
});
main = async () => {
await perry.save();
console.log(`success: user ${perry.firstName} added!`);
await tom.save();
console.log(`success: user ${tom.firstName} added!`);
};
main();
This issue happened due to disorder of functions calling in app.js file. All I used till now was a Mongodb and mongoose in noSQL. In the case of mongodb we can call the database config function after api endpoint specification. I wrote my code like this in couchbase. But it didn't stick in couchbase. I'll provide my code before and after fixing for more clarity, and I'm very sorry for my bad english. :)
Before fixing app.js file:
const express = require("express");
const cors = require("cors");
const morgan = require("morgan");
const app = express();
require("dotenv").config();
const PORT = process.env.PORT || 3000;
//middlewares
app.use(cors());
app.use(morgan("dev"));
app.use(express.json());
app.use(express.urlencoded({ extended: true }));
// routes
app.use("/api/", require("./routes/index"));
// bad requiest
app.use("*", (req, res) => {
res.status(404).json({ message: "Bad Requist." });
});
// error middleware
const { errorHandler } = require("./middlewares/error-middleware");
app.use(errorHandler);
// database setup
const db = require("./config/db");
db.connect();
// server setup
app.listen(PORT, (err) => {
if (err) {
console.log(err.message);
} else {
console.log(`The server is running on: ${PORT}.`);
}
});
After fixing app.js file:
const express = require("express");
const cors = require("cors");
const morgan = require("morgan");
const app = express();
require("dotenv").config();
const PORT = process.env.PORT || 3000;
//middlewares
app.use(cors());
app.use(morgan("dev"));
app.use(express.json());
app.use(express.urlencoded({ extended: true }));
// database setup
const db = require("./config/db");
db.connect();
// routes
app.use("/api/", require("./routes/index"));
// bad requiest
app.use("*", (req, res) => {
res.status(404).json({ message: "Bad Requist." });
});
// error middleware
const { errorHandler } = require("./middlewares/error-middleware");
app.use(errorHandler);
// server setup
app.listen(PORT, (err) => {
if (err) {
console.log(err.message);
} else {
console.log(`The server is running on: ${PORT}.`);
}
});

Returning data to a user from an external API

i am trying to return the value of my search after using the node-spotify-api package to search for an artist.when i console.log the spotify.search ..... without the function search function wrapped around it i get the values on my terminal..what i want is when a user sends a request to the userrouter routes i want is to display the result to the user..i using postman for testing ..
This is the controller
const Spotify = require('node-spotify-api');
const spotify = new Spotify({
id: process.env.ID,
secret: process.env.SECRET,
});
const search = async (req, res) => {
const { name } = req.body;
spotify.search({ type: 'artist', query: name }).then((response) => {
res.status(200).send(response.artists);
}).catch((err) => {
res.status(400).send(err);
});
};
module.exports = {
search,
};
**This is the route**
const express = require('express');
const searchrouter = express.Router();
const { search } = require('./spotify');
searchrouter.route('/').get(search);
module.exports = searchrouter;
**This is my server.js file**
const express = require('express');
require('express-async-errors');
const app = express();
require('dotenv').config();
// built-in path module
const path = require('path');
// port to be used
const PORT = process.env.PORT || 5000;
// setup public to serve staticfiles
app.use(express.static('public'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.set('port', PORT);
const searchrouter = require('./route');
app.use('/search', searchrouter);
app.get('/', (req, res) => {
res.sendFile(path.resolve(__dirname, 'index.html'));
});
app.listen(PORT, (req, res) => {
console.log(`Server is listening on port ${PORT}`);
});
[that is my project structure][1]
Well Your Code has a bug
Which is
searchrouter.route('/').get(search);
You are using a get request and still looking for a req.body
const { name } = req.body;
name is going to equal to = undefined
and when this runs
spotify.search({ type: 'artist', query: name })
it's going to return an empty object or an error
req.body is empty for a form GET request
So Your fix is
change your get request to a post
searchrouter.route('/').post(search);

TypeError: Tutorial is not a constructor

Im learning node js and MongoDB through a tutorial. Im creating a CRUD.
The connection with MongoDB is successful, but it shows this error: TypeError: Tutorial is not a constructor.
models/tutorial.model.js
const mongoose = require("mongoose");
const Tutorial = new mongoose.Schema({
title: String,
description: String,
published: Boolean
})
module.exports = mongoose.model("tutorial", Tutorial)
server.js
const express = require("express");
const bodyParser = require("body-parser")
const cors = require("cors")
const app = express();
const connectDB = require("./config/db")
var corsOptions = {
origin: "http://localhost:8081"
}
//connnect the database
if(connectDB()){
console.log("connected")
}
app.use(cors(corsOptions))
app.use(bodyParser.json())
app.use(bodyParser.urlencoded({ extended: true }))
app.get("/", (req, res) => {
res.json({ message: "Welcome to application" })
})
//setting the port
require("./routes/tutorial.routes")(app);
const PORT = process.env.PORT || 8080;
app.listen(PORT, () => {
console.log(`Server is running on port ${PORT}`)
})
controller/tutorial.controller.js
const db = require("../models")
const Tutorial = db.tutorials
//create and save
exports.create = (req, res) => {
//validate request
if(!req.body.title) {
res.status(400).send({message: "Content cannot be empty"})
}
const tutorial = new Tutorial({
title: req.body.title,
description: req.body.description,
published: req.body.published ? req.body.published : false
})
tutorial
.save(tutorial)
.then(data => {
res.send(data)
})
.catch(err => {
res.status(500).send({
message:
err.message || "Some error occured while creating the Tutorial"
})
})
}
How can I solve this error?
When you require a directory, node looks for the index.js file inside the directory.
This line:
const db = require("../models")
is loading your empty models/index.js file (could also be models.js but I would advise sticking with the index.js file as that's the standard)
This file should load all models and export them as an object:
module.exports = {
tutorial: require("./tutorial")
}
Which will allow you to use:
const db = require("../models")
const Tutorial = db.tutorial
note I dropped the s after db.tutorial to stay consistent and avoid typos.

Why I Can not get data from mongodb database?

It shows no error at all. Even cosole shows the database is connected. But it is not showing the data. When I go to http://localhost:5000/tasks it shows
Cannot GET /tasks
what am I missing here?
const express = require('express')
const bodyParser = require('body-parser');
const cors = require('cors');
const MongoClient = require('mongodb').MongoClient;
require('dotenv').config()
const uri = `mongodb+srv://${process.env.DB_USER}:${process.env.DB_PASS}#cluster0.vwtzw.mongodb.net/${process.env.DB_NAME}?retryWrites=true&w=majority`;
const app = express()
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cors());
const port =5000;
app.get('/', (req, res) => {
res.send('hello world!');
});
const client = new MongoClient(uri, { useNewUrlParser: true , useUnifiedTopology: true });
client.connect(err => {
const tasksCollection = client.db("VolunteerNetwork").collection("tasks");
app.get('/tasks',(req, res) => {
tasksCollection.find({})
.toArray( ( err, documents) => {
res.send(documents);
console.log(documents);
console.log('database connected');
})
})
});
app.listen(port);
after I run it shows -
undefined
database connected
mongo database name: VolunteerNetwork.tasks
the get route is inside the connect method - try reorganizing the code so that you open the connection when a request is made
const MongoClient = require('mongodb').MongoClient;
const uri = `mongodb://localhost:27017`;
const client = new MongoClient(uri, { useNewUrlParser: true , useUnifiedTopology: true });
router.get('/tasks',(req, res) => {
client.connect(err => {
const tasksCollection = client.db("VolunteerNetwork").collection("tasks");
tasksCollection.find({})
.toArray( ( err, documents) => {
res.send(documents);
console.log('database connected');
console.log(documents);
})
})
});
The code works perfectly fine. It is an accurate approach.
My mistake was I did not give access to the username to edit/read the database in MongoDB. Giving the privilege made the work done.

React gives me Cannot GET / page_name While reloading (node/express)

I am trying to build a reactjs app and I am trying to pass data through from my front end (react) to my backend (node/express). However I am getting an error when I try and view the page I get this error. (Cannot GET /home).
const express = require("express");
const app = express();
const port = 5000;
const cors = require("cors");
app.use(cors());
var bodyParser = require("body-parser");
app.use(bodyParser.json()); // to support JSON-encoded bodies
app.use(
bodyParser.urlencoded({
// to support URL-encoded bodies
extended: true
})
);
app.post("/home", (req, res) => {
const data = [(generalDetail = req.body.generalDetail)];
console.log(generalDetail, "has been added to /home");
res.json(data);
});
app.listen(port, () => `Server running on port ${port}`);
here is my onSubmit function:
onSubmitForm = e => {
e.preventDefault();
let data = {
generalDetail: this.state.generalDetails,
firstName: this.state.firstName,
middleName: this.state.middleName,
lastName: this.state.lastName
};
axios.post("http://localhost:5000/home", data).then(() => {
//do something
}).catch(() => {
console.log("Something went wrong. Plase try again later");
});
You dont have a get route for home, that is why you are having trouble.
Add the following code above your post route.
app.get("/home", (req, res) => {
console.log("here");
});

Resources