Im struggling to create API call to my database from node.js.
i have a postgres instance on Centos with multiple databases and table.
im trying to get table name "test_reslts" from database "sizing_results".
when the url, its just the server ip and port like http://{SERVER IP}:3300/
this is output -
"Cannot GET /"
when adding the table name or db name and table name, the request isn't completed and not output.
my code -
db_connection
const {Client} = require('pg')
const client = new Client({
user: 'postgres',
database: 'sizing_results',
password: 'password',
port: 5432,
host: 'localhost',
})
module.exports = client
api.js
const client = require('./db_connection.js')
const express = require('express'); // To make API calls
const app = express();
app.listen(3300, ()=>{
console.log("Server is now listening at port 3300");
})
client.connect();
app.get('/test_results', (req, res)=>{
client.query(`select * from test_results`, (err, result)=>{
if(!err){
res.send('BLABLA')
res.send(result.rows);
}
});
client.end;
})
Base on your answer to my comment I think it's not a DB connection problem.
It seems to be link to your routing, because it seems node never reach the inside of your route.
Are you sure you are calling the good route (http://localhost:3300/test_results) with no typo ? And with the good protocol (GET) ?
Related
So i built a frontend where you can fill in a movie name, a review and submit it to a database. Now im trying to connect a mysql database i created to the index.js , so that it gets filled with the first entry. Im trying to accomplish it like this:
const express = require('express');
const app = express();
const mysql = require('mysql');
const db = mysql.createPool({
host: "localhost",
user: "root",
password:"password",
database:'CRUDDatabase',
});
app.get('/', (req, res) => {
const sqlInsert = "INSERT INTO Movie_Reviews(movieName, movieReview) VALUES (1,'inception', 'good movie');"
db.query(sqlInsert, (err, result) =>{
res.send("change done");
});
})
app.listen(3001, () => {
console.log("running on port 3001")
})
But somehow the frontend gets the text ive send "Change done" but the database still doesnt show any entries. Any ideas where my mistake may be? Is it a code mistake or does it have to do with me db configuration. In mysql workbench i just created a default connection without changing anything.
EDIT: The Error seems to be the following:
Error: ER_NOT_SUPPORTED_AUTH_MODE: Client does not support authentication protocol requested by server; consider upgrading MySQL client
EDIT:
The following comment here solved my problem:
Execute the following query in MYSQL Workbench ALTER USER 'root'#'localhost' IDENTIFIED WITH mysql_native_password BY 'password'; Where root as your user localhost as your URL and password as your password Then run this query to refresh privileges: flush privileges; Try connecting using node after you do so. If that doesn't work, try it without #'localhost' part.
I think you have an error in your code but you are not showing it as you don't test in err variable, try this code in order to show what error you are getting:
const express = require('express');
const app = express();
const mysql = require('mysql');
const db = mysql.createPool({
host: "localhost",
user: "root",
password:"password",
database:'CRUDDatabase',
});
app.get('/', (req, res) => {
const sqlInsert = "INSERT INTO Movie_Reviews(movieName, movieReview) VALUES (1,'inception', 'good movie');"
db.query(sqlInsert, (err, result) =>{
if(err) {
console.log(err);
res.send(err.toString());
}
res.send("change done");
});
})
app.listen(3001, () => {
console.log("running on port 3001")
})
So as Med Amine Bejaoui pointed out in a comment, the solution is:
Execute the following query in MYSQL Workbench ALTER USER 'root'#'localhost' IDENTIFIED WITH mysql_native_password BY 'password'; Where root as your user localhost as your URL and password as your password Then run this query to refresh privileges: flush privileges; Try connecting using node after you do so. If that doesn't work, try it without #'localhost' part.
hy, I'm learning nodeJS but when do post using postman data is saving in db but not displaying response in POSTMAN. On postman just displaying sending request... .
const express = require("express")
const app = express()
// dbConnection
require('./mongo')
// Models
require('./model/Post')
// MIDDLEWARE
app.use(express.urlencoded({extended: true}));
app.use(express.json())
const mongoose = require('mongoose')
const Post = mongoose.model("Post")
// POST REQUEST
app.post('/posts', async (req, res)=>{
// res.send(req.body)
try{
const post = new Post()
post.title = req.body.title
post.content = req.body.content
data = await post.save()
res.json(data)
}catch(error){
res.status(500)
}
})
app.listen(8000, ()=>{
console.log('Server is running on port:8000')
})
I don't think you're even running on a port, it says here
console.log('Server is running on port:8000')
})
All you do is console.log Server is running on Port 8000 with no back tick, therefore your not even running your server. This is why I think your Code is not working, test it out and see, if you get an error then you can debug from there. At least put some effort into debugging rather than immediately going on stack overflow. replace what you done with the port with this
// Create a variable called port and set it to your desired port
const port = 8000;
// Then hook it up to express.
console.log(`Server is running on port: ${port}`)
})
If the problem is still there then I think I have the solution to it
Check if you have mongoose and express installed
(it's npm i mongoose express)
I don't think you're even connected to your mongoose server, try doing this
const express = require("express")
const app = express()
// dbConnection
require('./mongo')
// Models
require('./model/Post')
// MIDDLEWARE
app.use(express.urlencoded({extended: true}));
app.use(express.json())
const mongoose = require('mongoose')
const Post = mongoose.model("Post")
// Hook it up to res
const port = 8000
// POST REQUEST
app.post('/posts', async (req, res)=>{
// res.send(req.body)
try{
const post = new Post()
post.title = req.body.title
post.content = req.body.content
data = await post.save()
res.json(data)
}catch(error){
res.status(500)
}
})
// Mongoose Connection
mongoose
.connect("your connection (it should be connection to application on mongo)", {
useNewUrlParser: true,
useUnifiedTopology: true,
useFindAndModify: true
})
.then(() => {
console.log("Connected to the database");
})
.catch((err) => {
console.log(err);
});
app.listen(8000, ()=>{
console.log(`Server is running on port: ${port}`)
})
Then once you've finished that, you established a connection to the mongodb server and should send the request to post
I think the catch block is executed. In this block, you only set the status of the response to 500 but you don't actually send the response to the client. That's why the Postman screen keeps blocking.
So, there are 2 things:
you need to send something to the client
you need to log the error to debug.
app.post('/posts', async (req, res)=>{
// res.send(req.body)
try{
const post = new Post()
post.title = req.body.title
post.content = req.body.content
data = await post.save()
res.json(data)
}catch(error){
console.log(error);// for debugging
res.status(500).send("ERROR_SERVER"); // send something to client
}
})
I have found the answer for your error, as I said in my old answer, running your tests would've worked, and showed you the error, however I have found the answer, I am assuming you have already found the solution (which is probably the same solution as mine) but if you haven't here's the problem.
The problem
It's very simple, you're creating a variable for mongoose after you required mongoose require('./mongo'); const mongoose = require('mongoose') This is wrong as JavaScript and most programming languages read code line by line (if not then all) so change this up to be instead the following:
Solution
const mongoose = require('mongoose');
require('./mongo');
Information
Create the variable before you require the package like so (in your code example):
const mongoose = require('mongoose');
require('./mongo');
If you have more problems
If you do have more problems then try to reinstall/update the package dependency for mongoose as following:
yarn add mongoose
or
npm install mongoose
If you do still have problems after the only think I can ask you to do is to change the line of code when it says
require('./mongo');
to either
require('./{filename}'); // Whatever the actual filename is.
or:
require('./mongoose');
Tips to improving your question
Even if my question doesn't work for your code make sure to paste the error message or the important parts of the error message into the question, otherwise this makes it hard to pinpoint what your error is. This makes it easier to find the solution for your code.
I am working on an exercise tracker app using the MERN stack. I have a react JS component that is meant to allow me to add a new user to a database after I press the submit button. I am using axios to send http requests from my front end to server endpoint on the backend. However I keep getting this error
POST https://localhost:5000/users/add net::ERR_CONNECTION_REFUSED
Uncaught (in promise) Error: Network Error at createError
(0.chunk.js:971) at XMLHttpRequest.handleError (0.chunk.js:466)
This is my server side code
const express = require('express');
const cors = require('cors');
const mongoose = require('mongoose');
//mongoose is whats going to help us connect to our mongoDB database
require('dotenv').config();
//this configures si we can have our environment variables in the dotenv file
const app = express();
const port = process.env.PORT || 5000;
//this is how we will create our express server
app.use(cors());
app.use(express.json());
//this is our middle ware this will allopw us to parse json
// cause the server will be sending s=and receiving json
const uri = process.env.ATLAS_URI;
mongoose.connect(uri, {useNewUrlParser: true, useCreateIndex: true, useUnifiedTopology:true});
//uri is where database is stored
const connection = mongoose.connection;
connection.once('open',() =>{
console.log("MongoDB database connection established successfully");
});
//once connection is open its going to log the message
const exercisesRouter = require('./routes/excercises');
const usersRouter = require('./routes/users');
//importing
app.use('/excercises',exercisesRouter);
app.use('/users',usersRouter);
//use files
//whenever somebody goes to route url and put /excersies at the end it will show
//everything in excercises and the same for users
app.listen(port,()=>{
console.log('Server is running on port: ' + port);
});
//this is what starts the server. It start listening to a certain port
This is my submit function
onSubmit(e){
e.preventDefault(); //prevents default html form behaviour taking place
const user = {
username: this.state.username,
};
console.log(user);
//sending user data to the backend with post request
//check user.js file in routes its sending a post request to the user.add api
axios.post('https://localhost:5000/users/add',user)
.then(res => console.log(res.data));
this.setState({
username: ''
});
}
This is my route
router.route('/add').post((req,res) => {
const username = req.body.username;
const newUser = new User({username});
//using unsername to create new user
newUser.save()
.then(() => res.json('User added')) //after user saved to DB return user added message
.catch(err => res.status(400).json('Error ' + err)); //if there is an error return error
});
check if your backend is also running on port 5000 u need to start your backend
I followed this tutorial as well, you have to start the backend and the front end. The problem was the front end is only running that's why you can see everything( not sure how he managed ) but I had to pull up a terminal and start the front end with -> npm start and the backend with -> nodemon server on a separate terminal tab
bro, I think you did just a little mistake in your address which is
https://localhost:5000/users/add not https change it to http and it will solve your problem
your address will be http://localhost:5000/users/add
I have a question about the require function of Node.js, imagine we have a module that manages the connection, and many small modules that contain the routes.
An example of connection file: db.js
const mysql = require('mysql');
const connection = mysql.createConnection({
host : '127.0.0.1',
user : 'root',
password : '',
database : 'chat'
});
connection.connect(function(err) {
if (err) throw err;
});
module.exports = connection;
and one of the various files to manage the routes:
const app = express();
const router = express.Router();
const db = require('./db');
router.get('/save',function(req,res){
// some code for db
});
module.exports = router;
Imagine now to have 20 routes with the same require. How will node.js behave? How many times will my connection be created?
How many times will my connection be created?
There will be one connection, because "db.js" runs only once. The things you export get stored (module.exports) and that gets returned by every require("./db"). To verify:
require("./db") === require("./db") // true
I am new to programming for Web Applications
I am making a web service app using AJAX, mySQL, Node.js and Express.
I have made a database for mySQL and have connected it.
The problem i am facing is using AJAX to call mySQL data and to display it on my web-page using Node.JS / Express.
The code i have for the server and database connection:
app.js
var express = require('express');
var http = require('http');
var path = require('path');
//Import mySQL module
var mysql = require('mysql');
var app = express();
var bodyParser = require('body-parser');
app.use(bodyParser.urlencoded({extended: true}));
//Connection object using credentials
var con = mysql.createConnection({
host: "localhost",
user: "data",
password: "database",
database: "mydb"
});
//Connecting to the database
con.connect(
function(err){
if (err) throw err;
console.log("Database Connected");
}
);
con.end();
app.use(express.static(path.join(__dirname, '/public')));
app.get('/', function(req, res) {
res.sendFile(path.join(__dirname + '/index.html'));
});
app.listen(8080);
I will be creating a new js file to contain my AJAX code, however i do not know how to start constructing it. My aim is to use Node.js/Express to call information from my database into a table which i have formed using Bootstrap
Thanks