Empty body using express post - express

I can't seem to get the data from this post call. The body shows as an empty object {}.
I've tried several versions including these posts with no luck: Express.js req.body undefined
I've also tried different content-types, but that also hasn't worked.
Thoughts? Thanks in advance.
index.js:
const express = require('express')
const bodyParser = require('body-parser')
const app = express()
const db = require('./queries.js')
const port = 7000
// create application/json parser
var jsonParser = bodyParser.json()
// create application/x-www-form-urlencoded parser
var urlencodedParser = bodyParser.urlencoded({ extended: false })
app.get('/', (req, res) => {
res.json({
info: 'Node.js, Express, and Postgres API'
})
})
app.post('/jothook/', jsonParser, db.jothook)
app.listen(port, () => {
console.log(`App running on port ${port}.`)
})
queries.js:
const Pool = require('pg').Pool
const { req } = require('express');
const pool = new Pool({
user: 'testuser',
host: '167.XX.XX.XX',
database: 'testdb',
password: 'testpwd',
port: 5432,
})
const jothook = (req, res) => {
var qy = JSON.stringify(req.body);
var qy = 'INSERT INTO data_test VALUES ' + qy;
pool.query(qy, (error, results) => {
if (error) {
throw error
}
res.status(201).send(`Data Inserted`)
})
};
module.exports = {
jothook
};
post call:
{headers={Content-Type=application/json}, body="'test_data', 'joe', 'smith'", method=POST, mode=cors}

Related

How do I get back data from a database using express.js without the result being undefined

`I've been trying to display a database product with react but none of my approaches seem to work.
This is my node.js/express code :
const express = require('express');
const database = require('./config/database');
const bodyParser = require('body-parser');
const cors = require('cors');
const PORT = 3001;
const app = express();
app.use(express.json());
app.use(cors());
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.get('/products/:productId', (req, res) => {
console.log('request recieved');
const productId = req.params.productId;
const query = `SELECT * FROM products WHERE product_id = ${productId}`;
database.query(query, (err, result) => {
if (err) console.log(err);
console.log(result);
res.send(result);
});
});
app.listen(PORT, 'localhost');
I tried to fetch and log it with axios but the results are undefined :
const productId = params.productId;
const url = `/product/${productId}`;
const [{data, loading, error}] = useAxios(url);
console.log(data);
I also tried the regular approach :
const fetchProduct = async (url) => {
try {
const response = await fetch(url);
console.log(response);
const data = await response.json();
console.log(data);
} catch(err) {
console.log(err);
}
return data;
}
const product = fetchProduct(url);
console.log(product);`
Some help would be appreciated
What if you create an arrow-function that it returns a Promise
const getById = (productId) => {
const query = `SELECT * FROM products WHERE product_id = ${productId}`;
return new Promise((resolve, reject) => {
database.query(query, (err, result)=> {
err ? reject(err): resolve(result)
})
})
}
as our getById arrow-function returns a promise we need to async/await on it, so the app.get will be like this
app.get('/products/:productId', async(req, res) => {
console.log('request recieved');
const productId = req.params.productId;
const product = await getById(productId)
res.status(200).send(product)
});
One more thing, in your code you wrote
app.use(express.json());
and
app.use(bodyParser.json());
those two instruction do the SAME THING, so you need to delete one of them, and it better be the bodyParser one, because the body-parser is just deprecated and you don't need to install it, you just need to add
app.use(express.json())
app.use(express.urlencoded({ extended: true }))

getting Can't find / on this server while deploying my app on localhost

when I tried to connect my application with API I'm getting error in my localhost saying
"status": "fail",
"message": "Can't find / on this server",
"error": { statusCode: 404, status: "fail", isOperational: true },
"stack": "Error: Can't find / on this server\n at C:\\Users/*/*app.js:66",
here is my app.js
const express = require("express");
const morgan = require("morgan");
const rateLimit = require("express-rate-limit");
const helmet = require("helmet");
const mongoSanitize = require("express-mongo-sanitize");
const xss = require("xss-clean");
const hpp = require('hpp');
const AppError = require("./API/Utils/appError");
const globalErrorHsndler = require("./API/controllers/errorController");
const usersRouter = require("./API/routes/usersRoute");
const app = express();
app.use(express.json({ limit: "10kb" }));
// DATA SANITIZATION against NoSQL query injection
app.use(mongoSanitize());
// DATA SANITIZATION against site script XSS
app.use(xss());
// PREVENT PARAMETER POPULATION
app.use(
hpp({
whitelist: [
"duration",
"difficulty",
"price",
"maxGroupSize",
"ratingsAverage",
"ratingsQuantity",
],
})
);
// SECURE HEADER HTTP
app.use(helmet());
//RATE LIMIT
const apiLimiter = rateLimit({
windowMs: 60 * 60 * 1000, // 15 minutes
max: 100, // limit each IP to 100 requests per windowMs
message: "Too many requests, please try again later"
});
// apply to specific routes
app.use("/api", apiLimiter);
app.use(morgan("dev"));
//CUSTOM MIDDLE WARE
app.use((req, res, next) => {
console.log("Hey i am from middleware function πŸ‘‹");
next();
});
app.use((req, res, next) => {
req.requestTime = new Date().toISOString();
next();
});
app.use("/api/v1/users", usersRouter);
//ERROR SECTION
app.all("*", (req, res, next) => {
console.log(`Received request for url: ${req.originalUrl}`);
const error = new AppError(`Can't find ${req.originalUrl} on this server`, 404);
console.log(`Data inside next AppError: ${error}`);
next(error);
});
//GLOBAL ERROR HANDLEING
app.use(globalErrorHsndler);
module.exports = app;
here is my userRouter.js
const express = require("express");
const userControllers = require("./../controllers/userControllers");
const authController = require("./../controllers/authController");
const router = express.Router();
router.post("/signup", authController.signup);
router.post("/login", authController.login);
router.post("/forgotPassword", authController.forgotPassword);
router.patch("/resetPassword/:token", authController.resetPassword);
router.patch("/updateMyPassword", authController.protect, authController.updatePassword);
router.patch("/updateMe", authController.protect, userControllers.updateMe);
router.delete("/deleteMe", authController.protect, userControllers.deleteMe);
//ROUTERS USERS
router
.route("/")
.get(userControllers.getAllUsers)
.post(userControllers.createUser);
router
.route("/:id")
.get(userControllers.getSingleUser)
.patch(userControllers.updateUser)
.delete(userControllers.deleteUser);
module.exports = router;
and here is server.js
const dotenv = require("dotenv");
const mongoose = require("mongoose");
const app = require("./app");
const next = require("next");
const port = process.env.PORT || 3000;
const dev = process.env.NODE_ENV !== "production";
const server = next({ dev });
const handle = server.getRequestHandler();
process.on("uncaughtException", err=>{
console.log("uncaughtException Shutting down Application");
console.log(err.name, err.message);
process.exit(1);
});
dotenv.config({ path: "./config.env" });
const DB = process.env.DATABASE.replace(
"<PASSWORD>",
process.env.DATABASE_PASSWORD
);
mongoose
.connect(DB, {
useCreateIndex: true,
useFindAndModify: false,
useNewUrlParser: true,
})
.then((con) => {
console.log("DB Connection Successfully");
})
server.prepare().then(() => {
app.get("*", (req, res) => {
return handle(req, res);
});
app.listen(port, () => {
console.log(`App running on port ${port}....`);
});
});
process.on("unhandledRejection", (err) => {
console.log("unhandledRejection Shutting down Application");
console.log(err.name, err.message);
server.close(() => {
process.exit(1);
});
});
I need to ask from experts as I'm new to this

cookie-session, socket.io fails to store socket.id in sessions

server.js
const express = require("express");
const cookieSession = require("cookie-session");
const socketIo = require("socket.io");
const app = express();
app.use(
cookieSession({
name: "session",
keys: ["key1", "key2"],
})
);
app.use((req, res, next) => {
console.log(req.session);
next();
});
app.get("/", (req, res) => {
res.sendFile("./index.html", { root: __dirname });
});
app.get("/about", (req, res) => {
const connectionId = req.session.connectionId;
res.send(`About. connectionId: ${connectionId}`);
});
const server = app.listen(1234);
const io = socketIo(server);
io.on("connection", (socket) => {
const connectionId = Math.random().toString(36).substring(2);
socket.request.session.connectionId = connectionId;
// socket.request.session.save();
});
My problem is that when I call the connect event on the client, but on the server socket.request.session returns undefined so I can't set a unique value in the cookie-session. What is it connected with?

expressJS is preventing me to post a resource

I'm trying to build a mini app in express, the "database" I'm using is a local array object file, I can retrieve resources from this "database" but for some reason I'm not able to post (push) a new object to this object array. This is how the code looks like:
server.js:
const express = require('express');
const app = express();
const userRouter = require('./routes/user.js');
const port = process.env.PORT || 3000;
app.use(express.json());
app.use(express.text());
app.use('/user', userRouter);
app.listen(3000, () => console.log(`listening at ${port}`));
user.js:
const express = require('express');
const BBDD = require('./BBDD.js');
const userRouter = express.Router();
userRouter.get('/:guid', (req, res, next) => {
const { guid } = req.params;
const user = BBDD.find(user => user.guid === guid);
if (!user) res.status(404).send()
res.send(user);
next();
});
userRouter.post('/', (req, res, next) => {
let user = {};
user.name = req.body.name;
user.id = req.body.id;
BBDD.push(user);
next();
});
module.exports = userRouter;
And this is my local "database" file I want to perform logical CRUD operations:
BBDD.js
const BBDD = [{
index: 0,
guid: "1",
name: "Goku"
},
{
index: 1,
guid: "2",
name: "Vegeta"
},
];
module.exports = BBDD;
this is how I try to post a new resource, and this is the error I get:
It seems to be in order, but it won't work and can't find the bug.
Remove the next and send a response .express is having trouble finding the next matching handler because there is none

connect-history-api-fallback get cannot access

During setup of nodejs(as backend, port: 3333), and vuejs(frontend, port: 8080) environment, I was unable to access 'GET /article'. Also, when I remove connect-history-api-fallback, all I can see is json formatted database data.
How can I fix this?
Below is the code for app.js:
var express = require('express');
var app = express();
var history = require('connect-history-api-fallback');
app.use(history({
index: '/index.html',
verbose: true
}));
app.use(express.static(path.join(__dirname, 'public')));
// app.use(bodyParser.json());
var IndexRouter = require('./routes/index');
var ArticleRouter = require('./routes/article');
app.use('/', IndexRouter);
app.use('/article', ArticleRouter);
Below is the code for routes/article.js:
var express = require('express');
var router = express.Router();
var mysql = require('mysql');
router.get('/', function (req, res) {
console.log('article get μ ‘κ·Όν•˜μ˜€μŠ΅λ‹ˆλ‹€.');
pool.getConnection(function (err, connection) {
if (err) {
throw error;
}
const sqlQuery = 'SELECT * from board_article';
connection.query(sqlQuery, function (err, rows) {
if (err) {
connection.release();
throw error;
} else {
res.json(rows);
connection.release();
}
});
});
});