App.post doesn't send data to the database - javascript

I'm following a tutorial and I'm at the point where I'm trying to send a data to my MySQL database using the app.post. When I go to the localhost site running the request (my localhost is localhost:8800/shoes) it doesn't update/insert the data, it only shows the current database I have in MySQL. But in the video as the JS file was saved, the data got uploaded immediately.
import express from "express"
import mysql from "mysql"
const app = express()
const db = mysql.createConnection({
host: "localhost",
user: "root",
password: "qwerty",
database: "marketplace"
})
app.get("/", (req, res) => {
res.json("this is the backend")
})
app.get("/shoes", (req, res) => {
const q = "SELECT * FROM `marketplace`.`shoes`"
db.query(q, (err, data) => {
if(err) return res.json(err)
return res.json(data)
})
})
app.post("/shoes", (req, res) => {
const q = "INSERT INTO `marketplace`.`shoes` (`id`, `prod_name`, `prod_description`, `image`) VALUES(?)";
const values = [
"222",
"item3",
"item 3 description",
"item3 image"
];
db.query(q, [values], (err, data) => {
if(err) return res.json(err)
return res.json(data)
})
})
app.listen(8800, () => {
console.log("connected to backend")
})
I tried to troubleshoot it by removing the app.get and I receive in my localhost is Cannot GET /shoes.
import express from "express"
import mysql from "mysql"
const app = express()
const db = mysql.createConnection({
host: "localhost",
user: "root",
password: "qwerty",
database: "marketplace"
})
app.get("/", (req, res) => {
res.json("this is the backend")
})
// app.get("/shoes", (req, res) => {
// const q = "SELECT * FROM `marketplace`.`shoes`"
// db.query(q, (err, data) => {
// if(err) return res.json(err)
// return res.json(data)
// })
// })
app.post("/shoes", (req, res) => {
const q = "INSERT INTO `marketplace`.`shoes` (`id`, `prod_name`, `prod_description`, `image`) VALUES(?)";
const values = [
"222",
"item3",
"item 3 description",
"item3 image"
];
db.query(q, [values], (err, data) => {
if(err) return res.json(err)
return res.json(data)
//return res.json("test")
})
})
app.listen(8800, () => {
console.log("connected to backend")
})
So I suspect the issue is in the app.post but I have the same exact code in the video. I even tried the async and it still doesn't work
app.post("/shoes", async (req, res)
Please help what to do

From this part of your description
I tried to troubleshoot it by removing the app.get and I receive in my localhost is Cannot GET /shoes.
It sounds like when you're trying to add data to the shoes table and thus invoke the app.post() method you're actually still calling the get method.
Look at the frontend code that is attempting to save the data and make sure you have something like method: post in the options. Or if you're using a tool like Postman to test the API, make sure postman is configured with the post method.

Related

API POST request getting Error: Cannot read properties of undefined (reading 'job_title')

I have built and API with Express to POST a new job in a project I am currently working on. The GET requests work fine, also the DEL, but the POST one is not working. I am connected to a POSTGRES database.
I have defined the following path for the API:
app.use('/api/jobs', jobRoutes);
so when I send a POST request like below:
localhost:4000/api/jobs/createjob
it should work. What is also weird, is that the code was working perfectly before, but now I can't seem to figure it out anymore. I tried looking elsewhere, but I couldn't find any solution when getting this kind of error with APIs.
My API looks like the following:
router.post("/createjob", async (req, res) => {
try {
const {job} = req.body;
const newJob = await pool.query("INSERT INTO job(job_title, job_department, country_id, description, expiration_date) VALUES($1, $2, $3, $4, $5) RETURNING *", [job.job_title, job.job_department, job.country_id, job.description, job.expiration_date]);
res.json(newJob.rows);
} catch (error) {
console.error(error.message);
}
})
I am making the POST request with Postman, and the body looks like this:
{
"description": "job_description",
"job_title": "Back End Developer"
}
When I send the requests, in the terminal shows this error:
Cannot read properties of undefined (reading 'job_title')
Full code of the Routes:
const express = require("express");
const router = express.Router();
const pool = require("../db");
// routes
// get all jobs
router.get('/alljobs', async (req, res) => {
try {
const allJobs = await pool.query("SELECT * FROM job");
res.json(allJobs.rows)
} catch (error) {
console.error(error.message);
}
})
// GET a single job
router.get('/job/:id', async (req, res) => {
try {
const {id} = req.params;
const job = await pool.query("SELECT * FROM job WHERE job_id = $1 ", [id]);
res.json(job.rows)
} catch (error) {
console.error(error.message);
}
})
// create a job
router.post("/createjob", async (req, res) => {
try {
const {job} = req.body;
const newJob = await pool.query("INSERT INTO job(job_title, job_department, country_id, description, expiration_date) VALUES($1, $2, $3, $4, $5) RETURNING *", [job.job_title, job.job_department, job.country_id, job.description, job.expiration_date]);
res.json(newJob.rows);
} catch (error) {
console.error(error.message);
}
})
// update a job
router.patch("/updatejob/:id", async (req, res) => {
try {
const {id} = req.params;
const {description} = req.body;
const updateJob = await pool.query("UPDATE job SET description = $1 WHERE job_id = $2", [description, id]);
res.json(updateJob.rows);
} catch (error) {
console.error(error.message);
}
})
// delete a job
router.delete("/deletejob/:id", async (req, res) => {
try {
const {id} = req.params;
const deleteJob = await pool.query("DELETE FROM job WHERE job_id = $1", [id]);
res.json(deleteJob.rows);
} catch (error) {
console.error(error.message);
}
})
// get all countries
router.get("/countries", async (req, res) => {
try {
const allCountries = await pool.query("SELECT * FROM countries");
res.json(allCountries.rows)
} catch (error) {
console.error(error.message);
}
})
// //create new user
// router.post("/newuser", async (req, res) => {
// try {
// const {user} = req.body;
// const newUser = await pool.query("INSERT INTO users(user_name, email, password, is_candidate, is_recruiter) VALUES($1, $2, $3, $4, $5) RETURNING *", [user.user_name, user.email, user.password, user.candidate, user.recruiter]);
// res.json(newUser.rows);
// } catch (error) {
// console.error(error.message);
// }
// })
module.exports = router;
Full code of my server.js file:
const express = require("express");
const router = require("./routes/jobRoutes");
const jobRoutes = require("./routes/jobRoutes");
const cors = require("cors");
//creates express app
const app = express();
app.use(express.json());
app.use(cors());
//middleware
app.use((req,res,next) => {
console.log("req.path", req.method);
next();
})
app.get("/status", (req, res, next) => {
res.send("connected");
});
// for every other request
app.use('/api/jobs', jobRoutes);
// more middleware
app.use((err, req, res, next) => {
let status = err.status || 500;
let message = err.message;
console.error(err);
return res.status(status).json({
error: { message, status },
});
});
//listen for requests
app.listen(4000, () => {
console.log("listening on port 4000")
});
I tried looking elsewhere, but I couldn't find any solution when getting this kind of error with APIs. The GET and the DEL requests work as expected.

SQL data is not loading

Does anyone know why my request just gets stuck loading when trying to access my database ?
My database name is test. If set the database: books or something like that for example. Then it returns the error database is unknown: books so I assume that my password is correct it just isn't finding the test data base ?
// To import these packages remember to add "type":"module" to package Json
import express from "express";
import mysql from "mysql";
const app = express();
const db = mysql.createConnection({
host: "localhost",
user: "root",
password: "keks000207",
database: "test",
});
// This is an API request with an Express server
app.get("/", (req, res) => {
res.json("Hello this is the backend");
});
app.get("/books", (req, res) => {
const q = "SELECT * FROM books";
db.query(q, (err, data) => {
if (err) return res.json(err);
return data;
});
});
app.listen(8800, () => {
console.log("Connected to backend!");
});
Try db.connect() or similar method available in the file itself.
And Instead of return data inside the callback of db.query, you should use res.send(data), then you will get the response in the GET /books API.

Heroku gives me a CORS issue, but only after 20 mins of deploying. Before that, everything works fine

Hosting my first Node JS backend on Heroku today and ran into a weird issue. When I try to register/login right after deploying the backend, things work very smoothly, but if I try to register/login after about 15 minutes, I receive a CORS error. (I am using the cors dependency).
Here's my server code:
const express = require('express')
const mysql = require('mysql')
const cors = require('cors')
const bcrypt = require('bcrypt')
const app = express()
const saltRounds = 10
app.use(cors())
app.use(express.json())
app.post('/signup', (req, res) => {
const username = req.body.username
const password = req.body.password
bcrypt.hash(password, saltRounds, (err, hash) => {
if (err) {
console.log(err)
}
db.query("INSERT INTO users (username, password) VALUES (?, ?)", [username, hash],
(err, result) => {
console.log(err)
})
})
})
app.post('/login', (req, res) => {
const username = req.body.username
const password = req.body.password
db.query("SELECT * FROM users WHERE username = ?", [username], (err, result) => {
if (err) {
res.send({err: err})
}
if (result.length > 0) {
bcrypt.compare(password, result[0].password, (err, response) => {
if (response) {
res.send(result)
} else{
res.send({message: "Invalid Credentials"})
}
})
} else {
res.send({message: "User does not exist."})
}
})
})
Apologies if my code is formatted a bit strange, I always struggle with StackOverflow's code format.
Figured it out! mysql was timing out because I was using createConnection instead of createPool on my server.js. Hope this helps someone in the future!

Unable to post to my database mySQLWorkBench using express.js node.js

I am struggling to wrap my head around all this backend stuff. I basically have set up an amazon mySQL server with RDS and using mySQLWorkBench I have connected my express.js with the following file:
let mysql = require('mysql');
var connection = mysql.createConnection({
host: "",
user: "admin",
password: "",
});
connection.connect(function(err) {
if (err) throw err;
connection.query('CREATE DATABASE IF NOT EXISTS main;');
connection.query('USE main;');
connection.query('CREATE TABLE IF NOT EXISTS cars(id int NOT NULL AUTO_INCREMENT, manufacturer varchar(100), model varchar(100), price int, PRIMARY KEY(id));', function(error, result, fields) {
console.log(result);
});
connection.end();
});
module.exports = connection;
I already have my table set up in mySQLWorkbench, and and the connection is fine if I user the following in my server file:
connection.connect(function(err) {
if (err) {
console.error('Database connection failed: ' + err.stack);
return;
}
console.log('Connected to database.');
});
connection.end();
However in my Index.js, I am trying to create a post endpoint (im still very new to this and not sure where I should start etc, but I was following this tutorial: https://stackabuse.com/using-aws-rds-with-node-js-and-express-js/ ).
index.js:
const express = require('express');
const app = express();
const port = 3000;
const connection = require("./server");
app.listen(port, () => console.log("listening on port 3000") + port )
const dummyData = [
{manufacturer: "volvo", model: "1st", price: 300},
{manufacturer: "fiat", model: "500", price: 500},
];
app.post('/cars', (req, res) => {
if (req.query.manufacturer && req.query.model && req.query.price) {
console.log('Request received');
connection.connect(function(err) {
connection.query(`INSERT INTO main.cars (manufacturer, model, price) VALUES ('${req.query.manufacturer}', '${req.query.model}', '${req.query.price}')`, function(err, result, fields) {
if (err) res.send(err);
if (result) res.send({manufacturer: req.query.manufacturer, model: req.query.model, price: req.query.price});
if (fields) console.log(fields);
console.log(result)
});
});
} else {
console.log('Missing a parameter');
}
});
I am really not sure if I am doing this correctly, but when I run the file and host it, it's fine, then when I try use postman to do a post request with the following fields:
localhost:3000/cars?manufacturer=test&model=testmodel&price=2000
I get the following error:
{
"code": "PROTOCOL_ENQUEUE_AFTER_QUIT",
"fatal": false
}
My goal is here, is to have a few simple endpoints for my datastore, which is to post, retrieve and update. Any help for clarification or guides would be extremely appreicated. Thanks!

Deployed React Front-End not Communicating Node Back-End - Cpanel Configuration?

So I have a React frontend, and Node backend as my api connecting to mysql database. Everything works perfectly locally.
Now I have deployed to a c-panel VPS.
Front end loads as it should.
The back-end is listening, and prints out the data as it should if I type my IP address with routes into the address bar on a browswer.
However, I can get it to work typing the "domain-name + the routes". Can anyone tell me what's going on, and how to configure this is cPanel properly? I've spent days going in circles on this, and the hosting company support is no help at all.
here is a sample fetch call:
componentDidMount() {
fetch('/api/clients/all')
.then(res => {
if (!res.ok) {
throw new Error();
}
return res.json();
})
.then((result) => {
this.setState({
clients: result.sort((a, b) => a.client.localeCompare(b.client)),
});
console.log(result);
})
.catch(error => {
console.log(error);
})
.then(
fetch(`/api/contacts/all`)
.then(res => {
if (!res.ok) {
throw new Error();
}
return res.json();
})
.then((result) => {
this.setState({ contacts: result });
console.log(result);
})
.catch(error => {
console.log(error);
})
);
}
This is my server file with the routes in it.... I can't understand where my configuration is wrong. I think it may even be some cpanel configuration with the server, and not necessarily my code. Any help is appreciated.
const express = require('express');
const mysql = require('mysql2');
const cors = require('cors');
const connection = mysql.createPool({
connectionLimit: 10,
host : 'localhost',
user : 'root',
password : 'C5pkhi6r12!',
database : 'ppr'
});
const app = express();
app.use(express.json());
app.use(express.urlencoded({extended: false}));
app.use(cors());
app.use((req, res, next) => {
res.header('Access-Control-Allow-Origin', '*');
next();
});
app.get('/api/clients/all', function (req, res) {
// Connecting to the database.
connection.getConnection(function (err, connection) {
// Executing the MySQL query (select all data from the 'handbook' table).
connection.query("SELECT * FROM clients", function (error, results) {
// If some error occurs, we throw an error.
if (error) throw error;
// Getting the 'response' from the database and sending it to our route. This is where the data is.
console.log(results);
res.json(results);
});
connection.release();
});
});
app.get('/api/contacts/all', function (req, res) {
// Connecting to the database.
connection.getConnection(function (err, connection) {
// Executing the MySQL query (select all data from the 'handbook' table).
connection.query("SELECT * FROM contacts", function (error, results) {
// If some error occurs, we throw an error.
if (error) throw error;
// Getting the 'response' from the database and sending it to our route. This is where the data is.
// console.log(results);
res.json(results);
});
connection.release();
});
});
// Starting our server.
app.listen(8080, "0.0.0.0", () => {
console.log('Listening on port http://localhost:8080');
});
I might be late to answer, but this is how I did.
Add "Hostname": "https://YOURDOMAIN.XYZ" to package.json in react app.
Build your react app, and upload it to public_html
Use nodejs tool of cpanel.
Don't do app.listen(port, ........). Just use callback or leave it to app.listen()

Categories