BodyParser Express, I've got Object inside Object - express

I am trying post some data on a server but doesn't work because I am getting something like { '{\n "rate" : "26"\n}': '' }.
----App.js
const express = require('express'),
mongoose = require('mongoose'),
bodyParser = require('body-parser');
const db = mongoose.connect('mongodb://localhost/invoiceAPI');
app = express(),
port = process.env.PORT || 3000,
Rate = require('./models/rateModel'),
Client = require('./models/clientModel'),
Invoice = require('./models/invoiceModel');
app.use(bodyParser.urlencoded({extended: true}));
app.use(bodyParser.json());
const invoiceRouter = require('./routes/invoiceRoutes')(Invoice),
clientRouter = require('./routes/clientRoutes')(Client),
rateRouter = require('./routes/rateRoutes')(Rate);
app.use('/api/invoices', invoiceRouter);
app.use('/api/clients', clientRouter);
app.use('/api/rates', rateRouter);
app.listen(port, () => {
console.log('Gulp is running on port ' + port);
});
---The rateRoutes file:
const express = require('express');
const rateRoutes = (Rate) => {
const rateRouter = express.Router();
rateRouter.route('/')
.get((req,res) => {
Rate.find((err,rates) => {
if(err){
res.status(500).send(err);
}
else res.json(rates);
});
})
.post((req,res) => {
console.log(req.body);
let rate = new Rate(req.body);
rate.save();
res.status(201).send(rate);
});
return rateRouter;
}
module.exports = rateRoutes;
When I execute the post with {"rate": 26} I got
{ '{\n "rate" : "26"\n}': '' }
I read something about the order of bodyParser, but doesn't work.

Related

Empty body using express post

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}

Shopify (Node + React) custom app: verifyRequest() issue

I'm developing a custom embedded app with Node+React.
I followed the official tutorial but if I use the verifyRequest() middleware I always get the following error when I navigate through my app's pages:
Expected a valid shop query parameter
I really can't understand what's wrong with the code.
Could anyone please help me?
Below is the server.js code
require('isomorphic-fetch');
const dotenv = require('dotenv');
const Koa = require('koa');
const next = require('next');
const { default: shopifyAuth } = require('#shopify/koa-shopify-auth');
const { verifyRequest } = require('#shopify/koa-shopify-auth');
const { default: Shopify, ApiVersion } = require('#shopify/shopify-api');
const Router = require('koa-router');
const RedisSessionStorage = require('./middleware/RedisSessionStorage')
const Cookies = require('cookies')
dotenv.config();
Shopify.Context.initialize({
API_KEY: process.env.SHOPIFY_API_KEY,
API_SECRET_KEY: process.env.SHOPIFY_API_SECRET,
SCOPES: process.env.SHOPIFY_API_SCOPES.split(","),
HOST_NAME: process.env.SHOPIFY_APP_URL.replace(/https:\/\//, ""),
API_VERSION: ApiVersion.April21,
IS_EMBEDDED_APP: true,
SESSION_STORAGE: new Shopify.Session.CustomSessionStorage(
RedisSessionStorage.storeCallback,
RedisSessionStorage.loadCallback,
RedisSessionStorage.deleteCallback,
),
});
const port = parseInt(process.env.PORT, 10) || 3001;
const dev = process.env.NODE_ENV !== 'production';
const app = next({ dev });
const handle = app.getRequestHandler();
const ACTIVE_SHOPIFY_SHOPS = {[process.env.ACTIVE_SHOPIFY_SHOP]: process.env.SHOPIFY_API_SCOPES}
app.prepare().then(() => {
const server = new Koa();
const router = new Router();
server.keys = [Shopify.Context.API_SECRET_KEY];
server.use(
shopifyAuth({
accessMode: 'offline',
afterAuth(ctx) {
const { shop, scope, accessToken } = ctx.state.shopify;
global.accessToken = accessToken
ACTIVE_SHOPIFY_SHOPS[shop] = scope;
ctx.redirect(`/?shop=${shop}`);
},
}),
);
const handleRequest = async (ctx) => {
await handle(ctx.req, ctx.res);
ctx.respond = false;
ctx.res.statusCode = 200;
};
router.get("/", async (ctx) => {
const shop = ctx.query.shop;
if (ACTIVE_SHOPIFY_SHOPS[shop] === undefined) {
ctx.redirect(`/auth?shop=${shop}`);
} else {
await handleRequest(ctx);
}
});
router.get("(/_next/static/.*)", handleRequest);
router.get("/_next/webpack-hmr", handleRequest);
router.get("(.*)", verifyRequest({accessMode: 'offline'}), handleRequest);
server.use(router.allowedMethods());
server.use(router.routes());
server.listen(port, () => {
console.log(`> Ready on http://localhost:${port}`);
});
});
Have you tried with the default SESSION_STORAGE?
It looks like it's directing to /auth

Run socket.io from an express route

I have researched on this but nothing seems to satisfy my need. I have an express route connected to a mongodb. Below is part of the code.
const express = require('express');
const socketIo = require("socket.io");
const dbconnect = require("./models");
const handle = require("./handlers");
const routes = require("./routes");
const app = express();
app.use('/messages', routes.messages);
const PORT = 3000;
const server = app.listen(3000, function() {
console.log(`Listening on 3000`);
dbconnect().then(() => {
console.log("MongoDb connected");
});
});
const io = socketIo(server);
io.on('connection', function(client) {
console.log('Connected...');
});
My route looks like this:
const router = require('express').Router();
const handle = require('../handlers/messages');
router.post('/unread_messages', handle.unread_messages);
module.exports = router;
My handler looks like this:
const db = require("../models");
exports.unread_messages = async (req, res, next) => {
try {
const unreadmessages = await db.messages.countDocuments({ $and: [{receiver: req.body.receiver},
{ messageread: false }]});
return res.json({ unreadmessages });
} catch (err) {
return next({ status: 400, message: `Cannot get unread messages ${err}` });
}
};
I would like to add socket to the "/unread_messages" route so that I get an update of the count of unread messages in realtime. How do I do that?

UnhandledPromiseRejectionWarning: TypeError: io.emit is not a function

I am using Socket.io for real time image upload process but I got this error mentioned below. I'm writing socket and app.js logics in different files by referring this answer now i want to emit that socket events in controller files but got the error
UnhandledPromiseRejectionWarning: TypeError: io.emit is not a function
below is my code
app.js
// modules =================================================
var express = require('express');
var app = express();
const logger = require('morgan');
var bodyParser = require('body-parser');
const indexRouter = require("./routes/index");
const cors = require('cors');
const path = require("path");
const config = require("./environments/index");
var http = require('http').Server(app);
var sockets = require('./apis/socket.io');
// configuration ===========================================
var port = config.PORT || 8081; // set our port
sockets.getSocketIo(http);
app.use(bodyParser.json({ limit: '50mb' }));
app.use(bodyParser.urlencoded({
limit: '50mb',
extended: true,
parameterLimit: 50000
}));
app.use(cors());
app.use(logger('dev'))
app.use("/api", indexRouter);
app.use(express.static(path.join(__dirname, "/build")));
app.get('/', function (req, res) {
res.sendFile(__dirname + '/index.html');
});
http.listen(port, () => {
console.log('Magic happens on port ' + port); // shoutout to the user
});
exports = module.exports = app;
This is socket.io.js file code
var socketio = require('socket.io');
var io = {};
module.exports = {
getSocketIo: function (app) {
let userId = 1
io = socketio.listen(app);
io.sockets.on('connection', function (socket) {
console.log("new connection: " + socket.id);
console.log(socket)
console.log('socket connected')
// let rooms = socket.id
io.sockets.adapter.rooms
if (io.nsps['/'].adapter.rooms["room-" + userId] && io.nsps['/'].adapter.rooms["room-" +
userId].length > 0) userId++;
socket.join("room-" + userId);
//Send this event to everyone in the room.
io.sockets.in("room-" + userId).emit('connectToRoom', "You are in room no. " + userId);
io.sockets.in(userId).emit('Image_upload', "Image uploading is started");
console.log(socket.room)
console.log(socket)
});
}
};
This is controller code of api controller
report_data: async (req, res) => {
if (!req.body.id) {
logger.warn(error.MANDATORY_FIELDS);
return res.status(500).send(error.MANDATORY_FIELDS)
}
io.emit('progress', "Image is Uploading started Please Wait A minute");
io.emit('error', "clients connected!");
let Id = req.body.id;
let path = `tmp/daily_gasoline_report/${Id}`;
req.body.data_url = path
sequelize.sequelize.transaction(async (t1) => {
let result = error.OK
result.data = data
logger.info(result);
return res.status(200).send(result)
}).catch(function (err) {
logger.warn(err);
console.log(err)
return res.status(500).send(error.SERVER_ERROR)
})
},
You can Make changes like below in your file
app.js
// modules =================================================
var express = require('express');
var app = express();
const logger = require('morgan');
var bodyParser = require('body-parser');
const cors = require('cors');
const path = require("path");
const config = require("./environments/index");
var http = require('http').Server(app);
var io = require('socket.io').listen(http);
const indexRouter = require("./routes/index");
// configuration ===========================================
var port = config.PORT || 8081; // set our port
app.use(bodyParser.json({ limit: '50mb' }));
app.use(bodyParser.urlencoded({
limit: '50mb',
extended: true,
parameterLimit: 50000
}));
app.use(cors());
app.use(logger('dev'))
app.use("/api", indexRouter);
app.use(express.static(path.join(__dirname, "/build")));
app.get('/', function (req, res) {
res.sendFile(__dirname + '/index.html');
});
http.listen(port, () => {
console.log('Magic happens on port ' + port); // shoutout to the user
});
app.locals.io = io
exports = module.exports = app;
socket.io.js
let io;
const getSocketIo = (http) => {
let userId = 1
io = require('socket.io')(http);
io.sockets.on('connection', function (socket) {
io.sockets.adapter.rooms
if (io.nsps['/'].adapter.rooms["room-" + userId] && io.nsps['/'].adapter.rooms["room-" + userId].length > 0) userId++;
socket.join("room-" + userId);
//Send this event to everyone in the room.
io.sockets.in("room-" + userId).emit('connectToRoom', "You are in room no. " + userId);
console.log("new connection: " + socket.id);
console.log('socket connected')
});
}
module.exports = {
getSocketIo,
io
};
in your controllers add this code in api you have mentioned whenever you want to use socket add this code before using it
const io = req.app.locals.io;

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();
}
});
});
});