connect-history-api-fallback get cannot access - express

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

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}

Express. Failed to load resource: the server responded with a status of 404

I am trying to make a post request using router.post and I keep getting " the server responded with a status of 404.
I have a routes folder with the file usersRoute.js :
const express = require("express");
const router = express.Router();
const User = require("../models/userModel");
router.post("/login", async(req, res) => {
const { username, password } = req.body;
try {
const user = await User.findOne({ username, password });
if (user) {
res.send(user);
} else {
return res.status(400).json(error);
}
} catch (error) {
return res.status(400).json(error);
}
});
router.post("/register", async (req, res) => {
try {
const newuser = new User(req.body);
await newuser.save();
res.send("User registered successfully");
} catch (error) {
return res.status(400).json(error);
}
});
module.exports = router;
I'm also using this method to make a get request to another endpoint in a carsRoute.js file which looks like this (the get request works) :
const express = require("express");
const router = express.Router();
const Car = require("../models/carModel");
router.get("/getallcars", async(req,res) => {
try {
const cars = await Car.find()
res.send(cars)
} catch (error) {
return res.status(400).json(error);
}
})
module.exports = router;
Finally, I export them into server.js which looks like this :
const express = require('express');
const app = express();
const port = process.env.port || 5000;
const dbConnect = require('./db');
app.use(express.json())
app.use('/api/cars/' , require('./routes/carsRoute'))
app.use('/api/users/', require('./routes/usersRoute'))
app.get('/', (req,res) => res.send('Hello World') )
app.listen(port, () => console.log(`Node Js Server Started on port ${port}`))
I do not think i missed any "/" or have any additional ones.

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;

404 on API call in Thinkster MEAN Stack Tutorial

I'm following this Thinkster tutorial on building a reddit-esque web app using MEAN.
The tutorial instructs using curl to create a new post.
C:\root>curl --data "title=test&link=http://test.com" http://localhost:3000/posts
However, I get this error in response:
<h1>Not Found</h1>
<h2>404</h2>
<pre>Error: Not Found
at C:\root\app.js:30:13
at Layer.handle [as handle_request] (C:\root\node_modules\express\lib\router\layer.js:95:5)
at trim_prefix (C:\root\node_modules\express\lib\router\index.js:312:13)
at C:\root\node_modules\express\lib\router\index.js:280:7
at Function.process_params (C:\root\node_modules\express\lib\router\index.js:330:12)
at next (C:\root\node_modules\express\lib\router\index.js:271:10)
at C:\root\node_modules\express\lib\router\index.js:618:15
at next (C:\root\node_modules\express\lib\router\index.js:256:14)
at Function.handle (C:\root\node_modules\express\lib\router\index.js:176:3)
at router (C:\root\node_modules\express\lib\router\index.js:46:12)</pre>
I looked through those files, but all the references were just showing me what happens to the error...
Here's some code
/routes/index.js:
var express = require('express');
var router = express.Router();
/* GET home page. */
router.get('/', function(req, res, next) {
res.render('index', { title: 'Express' });
});
module.exports = router;
var mongoose = require('mongoose');
var Post = mongoose.model('Post');
var Comment = mongoose.model('Comment');
router.get('/posts', function(req, res, next){
Post.find(function(err,posts){
if(err){ return next(err); }
res.json(posts);
})
})
router.post('/posts', function(req,res,next){
var post = new Post(req.body);
post.save(function(err, post){
if(err){ return next(err); }
res.json(post);
})
})
/models/Posts.js:
var mongoose = require('mongoose');
var PostSchema = new mongoose.Schema({
title: String,
link: String,
upvotes: {type: Number, default: 0},
comments: [{type: mongoose.Schema.Types.ObjectId, ref: 'Comment'}]
});
mongoose.model('Post', PostSchema);
app.js:
var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var index = require('./routes/index');
var users = require('./routes/users');
var app = express();
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');
// uncomment after placing your favicon in /public
//app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use('/', index);
app.use('/users', users);
// catch 404 and forward to error handler
app.use(function(req, res, next) {
var err = new Error('Not Found');
err.status = 404;
next(err);
});
// error handler
app.use(function(err, req, res, next) {
// set locals, only providing error in development
res.locals.message = err.message;
res.locals.error = req.app.get('env') === 'development' ? err : {};
// render the error page
res.status(err.status || 500);
res.render('error');
});
module.exports = app;
var mongoose = require('mongoose');
require('./models/Posts');
require('./models/Comments');
mongoose.connect('mongod:localhost/news');
I feel like I did everything correct, except I wasn't sure where to place the additional routes in the routes index file, and similarly in app.js. But this seems negligible to me. I performed all the debugging I could think of but am stuck.
It should also be noted that this tutorial was perhaps not intended for use on a Windows machine. I had to install curl and do a few other things that perhaps wouldn't be necessary on a Linux or Mac. I am using Windows 10.
Your module.exports is called prematurely in routes/index.js. Move module.exports = router; to the bottom of your file, recycle your service, and try again.
Also there are issues with app.js. See below:
app.js:
var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
// Notice the differences starting here
var app = express();
var mongoose = require('mongoose');
// connect MongoDB
mongoose.connect('mongodb://localhost/news', function(err,db){
if (!err){
console.log('Connected to /news!');
} else{
console.dir(err); //failed to connect
}
});
require('./models/Posts');
require('./models/Comments');
var index = require('./routes/index');
var users = require('./routes/users');
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');
// uncomment after placing your favicon in /public
//app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use('/', index);
app.use('/users', users);
// catch 404 and forward to error handler
app.use(function(req, res, next) {
var err = new Error('Not Found');
err.status = 404;
next(err);
});
// error handler
app.use(function(err, req, res, next) {
// set locals, only providing error in development
res.locals.message = err.message;
res.locals.error = req.app.get('env') === 'development' ? err : {};
// render the error page
res.status(err.status || 500);
res.render('error');
});
module.exports = app;
routes/index.js:
var express = require('express');
var router = express.Router();
var mongoose = require('mongoose');
var Post = mongoose.model('Post');
var Comment = mongoose.model('Comment');
/* GET home page. */
router.get('/', function(req, res, next) {
res.render('index', { title: 'Express' });
});
router.get('/posts', function(req, res, next){
Post.find(function(err,posts){
if(err){
alert(err);
return next(err);
}
res.json(posts);
})
})
router.post('/posts', function(req,res,next){
var post = new Post(req.body);
post.save(function(err, post){
if(err){
alert(err);
return next(err);
}
res.json(post);
})
})
module.exports = router;

How to write into an Expressjs session with Primus

Using ExpressJs 4 and Primus, I can share the Express session.
primus.on('connection', function (spark) {
var req = spark.request; // Here, I have the Express session
req.session.foo = 'bar'; // I try to write into the session.
});
When I write the { foo: 'bar' } value into the session, I can't retrieve it from a standard http express call.
app.get('/api/...', function (req, res) {
console.log(req.session.foo); // Print undefined :'(
res.send();
});
The output is undefined. Could you explain me why?
Thanks.
According to the express-session documentation, we can save the session to the store.
https://github.com/expressjs/session#sessionsave
primus.on('connection', function (spark) {
var req = spark.request; // Here, I have the Express session
req.session.foo = 'bar'; // I try to write into the session.
req.session.save(); // Save the session to the store
});
Then, it works well!
Here's how I have it working currently (Express 4.13.4; Primus 4.0.5)
App.js
var express = require('express');
var cookieParser = require('cookie-parser');
var session = require('express-session');
var sockjs = require('sockjs');
var http = require('http');
var Primus = require('primus');
var realtime_functions = require('./custom_modules/realtime_functions.js');
var app = express();
var app_secret_key = 'app secret';
var cookieparser = cookieParser(app_secret_key);
var sessionstore = new session.MemoryStore();
app.use(cookieparser);
app.use(session({
secret: app_secret_key,
saveUninitialized: false,
resave: false,
store: sessionstore
}));
realtime_functions(app, cookieparser, sessionstore);
realtime_functions.js
var primus_start = function(express, cookies, store) {
var server = http.createServer(express);
var primus = new Primus(server, {transformer: 'SockJS', parser: 'JSON'})
primus.use('rooms', primusRooms)
server.listen(3000, '0.0.0.0');
primus.before('cookies', cookies);
primus.before('session', function session(req, res, next) {
try {
var sid = req.signedCookies['connect.sid'];
if (!sid) { return next(); }
req.pause();
store.get(sid, function (err, session) {
if (err) {
primus.emit('log', 'error', err);
return next();
}
if(session) {
req.sessionID = sid;
req.sessionStore = store;
req.thesession = store.createSession(req, session);
}
req.resume();
next();
});
} catch(error) {
console.log(error);
}
});
primus.on('connection', function(spark) {
spark.on('data', function(data) {
spark.request.thesession.addthis = "save this to session";
spark.request.thesession.save();
});
});
}
module.exports = primus_start;