I'm having a problem when I follow the Heroku tutorial with DB.
First error I got was that pg.connect was invalid from PSQL 7. I tried to change this and using pool instead. However, I can´t make it work and I don´t know why.
Client is 'null' so I get
Listening on 5000 C:\Users\a491601\OneDrive - AF\Privat\SHT\node-js-getting- started\index.js:21
client.query('SELECT * FROM test_table', function(err, result) {
TypeError: Cannot read property 'query' of null
Code:
const cool = require('cool-ascii-faces')
const express = require('express')
const path = require('path')
const PORT = process.env.PORT || 5000
var app = express();
app
.use(express.static(path.join(__dirname, 'public')))
.set('views', path.join(__dirname, 'views'))
.set('view engine', 'ejs')
.get('/', (req, res) => res.render('pages/index'))
.get('/cool', (req, res) => res.send(cool()))
.listen(PORT, () => console.log(`Listening on ${ PORT }`))
app.get('/db', function (request, response) {
var pg = require('pg')
var pool = new pg.Pool(process.env.DATABASE_URL)
pool.connect(function(err, client, done) {
client.query('SELECT * FROM test_table', function(err, result) {
done();
if (err)
{ console.error(err); response.send("Error " + err); }
else
{ response.render('pages/db', {results: result.rows} ); }
});
});
pool.end()
});
Please help me, I've tried different thing for hour now, but I can't get i right.
Related
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
};
so im developing website using nodejs, and then deploying it to microsoft azure, and using Azure Database for mysql server to be exact, and importing my databse using mysql workbench, now the problem is in the CORS, everyhting going well i run it on chrome and firefox in the same pc works fine, but when i try to acces the website using another pc, i get the error says "Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://localhost:3000/data/price%20asc. (Reason: CORS request did not succeed)".
heres my nodejs code:
//use path module
const path = require("path");
//use express module
const express = require("express");
//use hbs view engine
// const hbs = require('hbs');
//use bodyParser middleware
const bodyParser = require("body-parser");
//use mysql database
const mysql = require("mysql");
const app = express();
const db = require("./database");
//cors
const cors = require("cors");
// app.use(cors());
// app.use(
// cors({
// origin: "*",
// })
// );
app.use(function (req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.header(
"Access-Control-Allow-Headers",
"Origin, X-Requested-With, Content-Type, Accept"
);
next();
});
//konfigurasi koneksi
const conn = mysql.createConnection({
// host: 'localhost',
// user: 'root',
// password: '',
// database: 'domdom'
host: "domdom.mysql.database.azure.com",
user: "domdom#domdom",
password: "Banana123",
database: "schema1",
port: 3306,
ssl: true,
});
//connect ke database
conn.connect((err) => {
if (err) throw err;
console.log("Mysql Connected...");
});
//set views file
app.set("views", path.join(__dirname, "/"));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(express.json());
app.use(express.static(__dirname));
app.param("productname", function (request, response, next, product) {
// ... Perform database query and
// ... Store the user object from the database in the req object
request.product = product;
return next();
});
app.param("sort", function (request, response, next, price) {
// ... Perform database query and
// ... Store the user object from the database in the req object
request.price = price;
return next();
});
app.param("id", function (request, response, next, id) {
// ... Perform database query and
// ... Store the user object from the database in the req object
request.id = id;
ß;
return next();
});
//get all data
app.get("/data/:sort", (req, res) => {
let sql = "SELECT * FROM products Order By " + req.price;
let query = conn.query(sql, (err, results) => {
res.json(results);
});
});
//untuk search and sort
app.get("/data/:productname/:sort", function (req, res) {
let sql =
"SELECT * FROM products WHERE name like '%" +
req.product +
"%' Order By " +
req.price;
let query = conn.query(sql, (err, results) => {
res.json(results);
});
});
//untuk save data
app.post("/save/:id", (req, res) => {
let sql =
"INSERT INTO cart SELECT * from products WHERE id = '" + req.id + "'";
let query = conn.query(sql, (err, results) => {
if (err) throw err;
res.redirect("/");
});
});
//render interface
app.get("/", (req, res) => {
res.render("index");
});
//server listening
app.listen(3000, () => {
console.log("Server is running at port 3000");
});
as you can see in the code i have tried 3 ways trying to solve this problem, but nothing works, please help.
If you are using Azure app service to host your nodejs app,the most fastest way to config CORS on Azure Portal => app service => CORS :
I did some test on my side and this is my nodejs server code(as you can see, no config for CORS) :
const express = require('express')
const app = express()
const port = process.env.PORT || 8080
app.use(express.json())
app.get('/', (req, res) => {
res.send('Hello World!')
})
app.post('/', (req, res) => {
var body = req.body;
res.send(`Hello ${body.name}!`)
})
app.listen(port, () => {
console.log(`Example app listening at http://localhost:${port}`)
})
Test HTTP request from an local static web page:
<!DOCTYPE html>
<html>
<body>
<h1>The XMLHttpRequest Object</h1>
<button type="button" onclick="loadDoc()">Request data</button>
<p id="demo"></p>
<script>
function loadDoc() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("demo").innerHTML = this.responseText;
}
};
xhttp.open("POST", "https://nodeweb05.azurewebsites.net/", true);
xhttp.setRequestHeader("Content-type", "application/json");
var body = {"name":"testuser"};
xhttp.send(JSON.stringify(body));
}
</script>
</body>
</html>
You can try it yourself.
If you want to config CORS on code level, just try the config below:
const express = require('express')
const app = express()
var cors = require('cors')
app.use(cors())
I developed a bug tracker app using MERN, and on local, the interface updates in real time when the user performs CRUD operations using react hooks (state) and react context.
But once I deployed my app on google cloud, it seemed to turn into a static website, and if I add,edit, or delete, I have to refresh the page to see the change.
What could be causing this to happen?
Here is my server.js code:
require("dotenv").config();
const express = require("express");
const app = express();
const bodyParser = require("body-parser");
const cors = require("cors");
const mongoose = require("mongoose");
const ticketRoutes = express.Router();
const PORT = 8080;
var path = require("path");
let Ticket = require("./ticket.model");
app.use(cors());
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
mongoose.connect(process.env.MONGO_DB, { useNewUrlParser: true, useUnifiedTopology: true }, (error) => {
console.log(error);
});
const connection = mongoose.connection;
connection.once("open", function () {
console.log("MongoDB database connection established successfully");
});
ticketRoutes.route("/").get(function (req, res) {
Ticket.find(function (err, tickets) {
if (err) {
console.log(err);
} else {
res.json(tickets);
}
});
});
ticketRoutes.route("/:id").get(function (req, res) {
let id = req.params.id;
Ticket.findById(id, function (err, ticket) {
res.json(ticket);
});
});
ticketRoutes.route("/add").post(function (req, res) {
let ticket = new Ticket(req.body);
ticket
.save()
.then((ticket) => {
res.status(200).json({ ticket });
})
.catch((err) => {
res.status(400).send("adding new ticket failed");
});
});
ticketRoutes.route("/delete/:id").delete(function (req, res) {
Ticket.findByIdAndRemove(req.params.id, function (err, ticket) {
if (err) {
console.log(err);
return res.status(500).send({ ticket });
}
return res.status(200).send({ ticket });
});
});
ticketRoutes.route("/update/:id").post(function (req, res) {
Ticket.findById(req.params.id, function (err, ticket) {
if (!ticket) res.status(404).send("data is not found");
else ticket.ticket_name = req.body.ticket_name;
ticket.ticket_status = req.body.ticket_status;
ticket
.save()
.then((ticket) => {
res.json({ ticket });
})
.catch((err) => {
res.status(400).send("Update not possible");
});
});
});
app.use("/tickets", ticketRoutes);
app.use(express.static(path.join(__dirname, "frontend/build")));
app.get("/*", (req, res) => {
res.sendFile(path.join(__dirname, "frontend/build/index.html"));
});
app.listen(process.env.port || 8080, () => {
console.log("Express app is running on port 8080");
});
The fix was very in depth, but basically my method of deployment to google cloud was a method that would only work with static web pages. I ended up deploying the app with heroku using this great guide: enter link description here
var express = require("express");
var app = express();
var bodyParser = require('body-parser');
var port = 3000;
const fs = require('fs');
// we are connecting to the mangodb using mangoose
var mongoose = require("mongoose");
// Now we are using bodyParser
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
mongoose.connect("mongodb://localhost:27017/YourDB", { useNewUrlParser: true })
// now we are creating the schema to the database
var nameSchema = new mongoose.Schema({
firstName: String,
lastNameName: String
});
// Now we have to create a model
var User = mongoose.model("User", nameSchema);
app.use("/", (req, res) => {
res.sendFile(__dirname + "/index.html");
});
// Now we are posting the data
app.post("/addname", (req, res) => {
console.log("nnnnnn")
console.log(req.body.firstName)
var myData = new User(req.body);
myData.save()
console.log(myData);
fs.writeFile(__dirname +"/data.json",myData, function(err){
if(err) {
return console.log(err);
}
console.log("The file is saved ");
})
console.log(myData)
})
// Now we are getting the data
app.listen(port, () => {
console.log("Server listening on port " + port);
});
1)I am using express app.post to post the data into database and store the data into the write file to check
2) app.post is not working it tried console.log to check but it is not going inside the function
3) I am not getting output as well as any error plese help me
there is no error handling and response handling in this code.
it will be readable if we write post method with async/await :
app.post("/addname", async (req, res) => {
console.log("nnnnnn")
console.log(req.body.firstName)
var myData = new User(req.body);
await myData.save()
console.log(myData);
fs.writeFileSync(__dirname +"/data.json", myData)
console.log(myData)
})
you will add next() to app.use
var User = mongoose.model("User", nameSchema);
app.use("/", (req, res,next) => {
res.sendFile(__dirname + "/index.html");
next()
});
// Now we are posting the data
app.post("/addname", (req, res) => {
console.log("nnnnnn")
console.log(req.body.firstName)
var myData = new User(req.body);
myData.save()
console.log(myData);
fs.writeFile(__dirname +"/data.json",myData, function(err){
if(err) {
return console.log(err);
}
console.log("The file is saved ");
})
console.log(myData)
})
// Now we are getting the data
app.listen(port, () => {
console.log("Server listening on port " + port);
});
That's because every request is going to this app.use code block. app.use("/", (req, res) => { ... });
Just Put it below the app.post("/addname", (req, res) => { ... });
app.use is used to mount middlewares into the request-response chain. So, every request that comes matches the /(which is essentially every request) goes inside that middleware. So, use your routes first then use the middleware at the end.
EDIT:
Let me give you a mcve which I tested locally:
const express = require('express');
const fakeData = function(){
return {
s: "fakeData"
}
}
const app = express();
const port = 8181
const path = require('path')
app.get("/a", (req, res) => {
return res.json({d:'yay'});
});
app.use('/',(req,res)=>{
return res.json(fakeData());
})
app.listen(port, () => {
console.log(`Server started on PORT ${port}`);
});
Because every request goes through a mounted middleware, so when you GET/POST/ANYTHING to localhost:8181/<abosulutely_any_path> it will go through the app.use because it treats that function as middleware and will return { s: "fakeData" }.
But when you make a GET call http://localhost:8181/a it will go to the app.get route BECAUSE WE DECLARED IT FIRST and return { d : "yay" }
I'm passing a data of a variable in URl from an python as
response = urlopen("localhost:5000/warehouse?fruitid=103456",timeout=10);
data = json.loads(response.read().decode('utf8'));
And it reading the response in json format for further processing.
How can I write the node.js routing for posting the data which reads the passed variable value of fruitid=103456 and insert the timestamp into the database when this request occurs.
Please help me out__...
try this - i use this to parse out json responses from other sources...
import pandas as pd
data1=dict(field1=data['field1_in_response'], field2=data['field2_in_response'],...);
data1=pd.DataFrame(data1)
print(data1)
const express = require('express');
const app = express();
const port = 5000;
var mysql = require('mysql')
var squel = require("squel");
var connection = mysql.createConnection({
host: 'localhost',
user: 'root',
password: 'toor',
database: 'invoice'
});
app.get('/warehouse', (req, res) => {
let fruitid = req.query.fruitid;
let queryDashboard = "select * from fruit where fruitid ='"+fruitid +"'";
connection.query(queryDashboard, function (err, rows, fields) {
if (err) throw err
console.log('query get successful');
var result = rows.map(data => data.name);
res.send(result);
// connection.end()
})
});
app.listen(port, () => console.log(`Example app listening on port ${port}!`));`enter code here`
Here's how you could handle this kind of request in an Express/MongoDB app:
const express = require('express');
const MongoClient = require('mongodb').MongoClient;
const app = express();
const port = 5000;
app.get('/warehouse', (req, res) => {
console.log('fruitid:', req.query.fruitid);
MongoClient.connect('mongodb://localhost:27017', function (err, client) {
if (err) throw err;
const db = client.db('mydatabase');
db.collection('fruits').find({ id: req.query.fruitid }).toArray(function (err, result) {
if (err) throw err;
res.json(result);
});
});
});
app.listen(port, () => console.log(`Example app listening on port ${port}!`));