express js - GET request 404 not found when using sequelize - mysql

I am using Sequelize and express.js in server development.
When I try to send GET request for route /files, an error shows:
{
"errors": {
"message": "Not Found",
"error": {
"status": 404
}
}
}
Folder structure
src
-models
-File.js
-routes
-api
-index.js
-files.js
-index.js
-app.js
-sequelize.js
package.json
I am trying to get ALL records from table files
/src/routes/api/files.js
const router = require('express').Router();
const Files = require('../../models/File')
router.get('/files', (req,res) =>
Files.findAll()
.then(data => {
res.sendStatus(200)
})
.catch(err => console.log(err))
);
module.exports = router;
/src/routes/index.js
var router = require('express').Router();
router.use('/api', require('./api'));
module.exports = router;
/src/models/File.js
const Sequelize = require('sequelize');
const DataTypes = Sequelize.DataTypes;
const db = require('../sequelize')
let files = db.define('files', {
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
allowNull: false,
primaryKey: true
},
fileName: {
type: DataTypes.STRING
},
});
module.exports = files;
src/sequelize.js
const { Sequelize } = require('sequelize');
const sequelize = new Sequelize('myDb', 'admin', '1234', {
dialect: 'mysql',
logging: false
});
sequelize.sync({alter: true})
module.exports = sequelize;
src/app.js
var http = require('http'),
path = require('path'),
methods = require('methods'),
express = require('express'),
bodyParser = require('body-parser'),
session = require('express-session'),
cors = require('cors'),
passport = require('passport'),
errorhandler = require('errorhandler'),
mongoose = require('mongoose');
const sequelize = require('./sequelize')
sequelize.authenticate()
.then(() => {console.log("connected")}) //printed "connected"
.catch((err) => {console.log(err)})
var isProduction = process.env.NODE_ENV === 'production';
var app = express();
app.use(cors());
app.use(require('morgan')('dev'));
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
app.use(require('method-override')());
app.use(express.static(__dirname + '/public'));
app.use(session({ secret: 'conduit', cookie: { maxAge: 60000 }, resave: false, saveUninitialized: false }));
if (!isProduction) {
app.use(errorhandler());
}
if(isProduction){
mongoose.connect(process.env.MONGODB_URI);
} else {
mongoose.connect('mongodb://localhost/conduit');
mongoose.set('debug', true);
}
require('./models/File');
app.use(require('./routes'));
/// catch 404 and forward to error handler
app.use(function(req, res, next) {
var err = new Error('Not Found');
err.status = 404;
next(err);
});
if (!isProduction) {
app.use(function(err, req, res, next) {
console.log(err.stack);
res.status(err.status || 500);
res.json({'errors': {
message: err.message,
error: err
}});
});
}
app.use(function(err, req, res, next) {
res.status(err.status || 500);
res.json({'errors': {
message: err.message,
error: {}
}});
});
var server = app.listen( process.env.PORT || 3000, function(){
console.log('Listening on port ' + server.address().port);
});
Update 1
src/routes/api/index.js
var router = require('express').Router();
router.use('/', require('./users'));
router.use('/files', require('./files'));
router.use(function(err, req, res, next){
if(err.name === 'ValidationError'){
return res.status(422).json({
errors: Object.keys(err.errors).reduce(function(errors, key){
errors[key] = err.errors[key].message;
return errors;
}, {})
});
}
return next(err);
});
module.exports = router;

Edit
In your /api/index.js file you have :
router.use('/files', require('./files'));
So the URL should be: http://localhost:3000/api/files/files
If you want to change the URL to: http://localhost:3000/api/files, in your files.js, you should change to :
router.get('/', (req,res) => // change "/files" to just "/"
Files.findAll()
.then(data => {
res.sendStatus(200)
})
.catch(err => console.log(err))
);

Related

Module not found: Can't resolve 'fs' in '.../node_modules/destroy' using Next.js mysql Express React

I would like to insert data from pages/index.js into mysql database.
A mysql connection in routes/routes.js, i have built ins function to call what i want
Structure
components
pages
index.js
routes
routes.js
server.js
package.json
Fail with error:
Module not found: Can't resolve 'fs' in '.../node_modules/destroy'
pages/index.js
import React, { Component } from "react";
import { Typography, Button, Grid } from "#material-ui/core";
import QRCode from "qrcode.react";
import dynamic from "next/dynamic";
import { PublicKey, SecretKey, HOSPCODE } from "../stellar";
const { ins } = require("../routes/routes"); //This is the problem!
const StellarSdk = require("stellar-sdk");
const QrReader = dynamic(() => import("react-qr-reader"), {
ssr: false
});
export default class QR extends Component {
state = {
result: "",
camera: true,
msg: "",
QR: {}
};
_clear = () => {
this.setState({ result: "", camera: true, msg: "", QR: {} });
};
handleScan = data => {
if (data) {
const dataJson = JSON.parse(data);
if (dataJson.Type == "Patient") {
const KP = StellarSdk.Keypair.fromSecret(SecretKey);
this.setState({
result: dataJson,
QR: JSON.stringify({
Type: "Hospital",
HospitalName: "xxx Hospital",
EndPoint: "xxx/patientID_",
SPK: PublicKey,
Signature: KP.sign(
Buffer.from(dataJson.ID + dataJson.SPK)
).toString("base64")
}),
camera: false,
msg: ""
});
ins(dataJson.ID, HOSPCODE, dataJson.SPK, dataJson.SecretKey);
} else {
this.setState({
msg: "Wrong QRCode."
});
}
}
};
But /routes/routes in server.js work.
const express = require("express");
const next = require("next");
const dev = process.env.NODE_ENV !== "production";
const app = next({ dev });
const handle = app.getRequestHandler();
const bodyParser = require("body-parser");
const { router, ins } = require("./routes/routes");
app
.prepare()
.then(() => {
const server = express();
server.use(bodyParser.json());
server.use(bodyParser.urlencoded({ extended: false }));
server.use("/api", router);
server.get("*", (req, res) => {
return handle(req, res);
});
server.listen(3001, err => {
if (err) throw err;
console.log("> Ready on http://localhost:3001");
});
})
.catch(ex => {
console.error(ex.stack);
process.exit(1);
});
routes/routes.js
const express = require("express");
const mysql = require("mysql");
const router = express.Router();
const dotenv = require("dotenv").config();
const connection = mysql.createConnection({
host: process.env.DATABASE_HOST,
database: process.env.DATABASE_NAME,
user: process.env.DATABASE_USERNAME,
password: process.env.DATABASE_PASSWORD,
port: 3306
});
console.log("Connecting...");
connection.connect(function(err) {
if (err) return new Error("An error occured during SQL connection " + err);
console.log("Connected!");
});
console.log(connection.config);
/* GET home page. */
router.get("/", function(req, res, next) {
...
...
...
ins = (cid, HOSPCODE, spk, secretKey) => (cid, HOSPCODE, spk, secretKey) => {
var sql = "INSERT INTO STELLARKEY (CID, HOSPCODE, SPK, SecretKey) VALUES ?";
var values = [[cid, HOSPCODE, spk, secretkey]];
connection.query(sql, [values], function(err, result) {
if (err) throw err;
});
};
module.exports = { router, ins };
I am new at Next.js and React. There is a better way to insert data from pages/index.js into mysql database? Please let me know.
"dependencies": {
"#material-ui/core": "^4.9.0",
"#material-ui/icons": "^4.5.1",
"body-parser": "^1.19.0",
"dotenv": "^8.2.0",
"express": "^4.17.1",
"fs": "^0.0.1-security",
"mysql": "^2.18.1",
"next": "^9.2.1",
"qrcode.react": "^1.0.0",
"react": "^16.12.0",
"react-dom": "^16.12.0",
"react-qr-reader": "^2.2.1",
"stellar-sdk": "^3.3.0",
"typeface-roboto": "^0.0.75"
}
Ubuntu 18.04 x64,
mysql Ver 14.14 Distrib 5.7.28,
Node v12.14.1
At last, i have to post request to my server via the same server on frontend(index.js) to insert data into mysql database.
I'm not sure. because of SSR(Next.js), i cannot send data back to backend.
But
I still need other method except post request into itself.
routes/routes.js
router.post("/secret/", cors(corsOptions), function(req, res, next) {
var sql = "INSERT INTO STELLARKEY (CID, HOSPCODE, SPK, SecretKey) VALUES ?";
var values = [
[req.body.cid, req.body.HOSPCODE, req.body.spk, req.body.secretkey]
];
connection.query(sql, [values], function(err, result) {
if (err) console.log(err);
});
});
module.exports = router;
pages/index.js
fetch("http://localhost:3001/api/secret", {
method: "POST",
headers: {
Accept: "application/json",
"Content-Type": "application/json"
},
body: JSON.stringify({
cid: dataJson.ID,
HOSPCODE: HOSPCODE,
spk: dataJson.SPK,
secretkey: dataJson.SecretKey
})
});
server.js
const router = require("./routes/routes");
app
.prepare()
.then(() => {
const server = express();
server.use(bodyParser.json());
server.use(bodyParser.urlencoded({ extended: false }));
server.use("/api", router);
server.get("*", (req, res) => {
return handle(req, res);
});
As long as we don't run next build and don't start app with NODE_ENV=production, this issue won't happen.
We use NODE_ENV=dev to circumvent this issue for the moment. I mean we use npm run dev to deploy now. This can only be considered a temporary solution.
"scripts": {
"dev": "NODE_ENV=dev node server.js",
"start": "node server.js",
"deploy": "next build && NODE_ENV=production node server.js"
}

How to import mysql connection in another file in nodejs?

I am not able to import the mysql connection file from the parent file to another file for making a DB connection.
I can connect to DB if the query is written in same file, if i try to hit the same query in another file then i get "TypeError: connection.query is not a function" error. Not able to access any functions of the connection object.
this is my server.js file:
var express = require('express');
var cors = require('cors');
var mysql = require('mysql');
app = express(),
app.use(cors()),
port = process.env.PORT || 3001;
bodyParser = require('body-parser');
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
config = {
host: 'localhost',
user: 'root',
password: '',
database: '<DB name>'
}
var connection = mysql.createConnection(config);
connection.connect(function(err){
if (err){
console.log('error connecting:' + err.stack);
}
console.log('connected successfully to DB.');
});
var routes = require('./api/routes/routes'); //importing route
routes(app);
console.log('todo list RESTful API server started on: ' + port);
app.listen(port);
module.exports= connection;
This is my api.js file:
'use strict';
var connection = require('../../server.js');
connection.query ('select * from <table name>', function(error, results){
if (results){
console.log(results);
}
else{
console.log(error);
}
});
or
exports.get=function(req,res){
console.log(req.query.printerModel);
console.log('inside get function');
connection.query('select * from inkdetails', function(error, results){
if (results){
res.status(200).send(inkdetails)
console.log(results);
}
else{
res.status(400).send(error)
console.log(error);
}
});
};
Create a file which will handle connection and export required utility functions related to mysql and then you can initialize connection in your startup file and import that connection object in any handler.
your mysql lib:
const mysql = require('mysql');
const logger = require('your-looger-path');
const mysqlConfig = {
host: 'localhost',
user: 'root',
password: '',
database: '<DB name>'
}
var pool = mysql.createPool(mysqlConfig);
module.exports.connect = function (cb) {
return new Promise((resolve, reject) => {
pool.on('connection', function (connection) {
connection.on('error', function (err) {
logger.error('MySQL error event', err)
});
connection.on('close', function (err) {
logger.warn('MySQL close event', err)
});
});
resolve()
})
}
async function executeQuery (query) {
logger.debug(`query: `, query)
return new Promise((resolve, reject) => {
try{
pool.query(query, (e, r, f) => {
if(e){
reject(e)
}
else{
logger.debug(r,f)
resolve(r[0])
}
});
}
catch(ex){
reject(ex)
}
})
}
async function execSP(spName, params){
return new Promise((resolve, reject) => {
try{
var paramPlaceHolder = ''
if(params && params.length){
for(var i = 0; i < params.length; i++){
paramPlaceHolder += '?,'
}
}
if(paramPlaceHolder.length){
paramPlaceHolder = paramPlaceHolder.slice(0, -1)
}
logger.debug('final SP call', `CALL ${spName}(${params})`)
pool.query(`CALL ${spName}(${paramPlaceHolder})`, params, (e, r, f) => {
if(e){
reject(e)
}
else{
resolve(r[0])
}
});
}
catch(ex){
reject(ex)
}
})
}
module.exports.executeQuery = executeQuery
module.exports.execSP = execSP
and then create the connection in server.js file:
var express = require('express');
var cors = require('cors');
var mysqllib = require('require to your mysql wrapper created above');
app = express(),
app.use(cors()),
port = process.env.PORT || 3001;
bodyParser = require('body-parser');
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
mysqllib.connect().then(() => {
console.log('Connected to mysql...')
var routes = require('./api/routes/routes'); //importing route
routes(app);
console.log('todo list RESTful API server started on: ' + port);
app.listen(port);
}).catch(e => {
console.error('Error connecting mysql...')
process.exit()
})
In your controller
'use strict';
const mysqlLib = require('your mysql lib path')
exports.get = function(req, res){
console.log(req.query.printerModel);
console.log('inside get function');
mysqlLib.executeQuery('select * from inkdetails').then((d) => {
console.log(d);
res.status(200).send(d)
}).catch(e => {
console.log(e);
res.status(500).send('Sorry, something went wrong!')
})
};
Hopes this help you.
create a config folder and create a file databaseConfig.js
var mysql = require('mysql');
config = {
host: 'localhost',
user: 'root',
password: '',
database: '<DB name>'
}
var connection =mysql.createConnection(config); //added the line
connection.connect(function(err){
if (err){
console.log('error connecting:' + err.stack);
}
console.log('connected successfully to DB.');
});
module.exports ={
connection : mysql.createConnection(config)
}
app.js
var express = require('express');
var cors = require('cors');
app = express(),
app.use(cors()),
port = process.env.PORT || 3001;
bodyParser = require('body-parser');
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
var routes = require('./api/routes/routes'); //importing route
routes(app);
console.log('todo list RESTful API server started on: ' + port);
app.listen(port);
controller.js
var config = require('../../databaseConfig.js');
var connection= config.connection
connection.query ('select * from <table name>', function(error, results){
if (results){
console.log(results);
}
else{
console.log(error);
}
});

React-Native JSON Parse error: Unexpected identifier "var"

Im trying to make a login screen for my react-native app, but when I try to login I get the error message 'JSON Parse error: unexpected token "var" ' displayed.
I have a react native app and a server app in a different folder which I acces via localhost.
I have tried to change var to let to see what would happen, but then I would get the same error, but with let instead.
This is my react-native code
login = () => {
fetch('http://192.168.0.105:8888/loginbackend/routes/users.js', {
method: 'POST',
header: {
'Content-Type': 'application/json',
'Accept': 'application/json',
},
body: JSON.stringify({
username: this.state.username,
password: this.state.password,
})
})
.then((response) => response.json())
.then ((res) => {
if (res.success === true) {
AsyncStorage.setItem('user', res.user);
this.props.navigation.navigate('Profile');
}
else {
alert(res.message);
}
})
.done();
}
}
My server file
var express = require('express');
var router = express.Router();
var mysql = require('mysql');
var connection = mysql.createConnection({
host: 'localhost',
user: 'root',
password: 'root',
database: 'users'
});
router.POST('/', function(req, res) {
var username = req.body.username;
var password = req.body.password;
connection.query(
"SELECT * FROM user WHERE username = ? AND password = ?",
[username, password], function (err, row){
if (err) {
console.log(err);
res.send({ 'success': false, 'message': 'Kan niet met de database verbinden'});
}
if (row.length > 0 ){
res.send({ 'success': true, 'user': row[0].username });
} else {
res.send({ 'success': false, 'message': 'Gebruiker niet gevonden'});
}
});
});
module.exports = router;
Before, I got JSON Parse error: unexpected token '<', but now its JSON Parse error: unexpected identifier "var". I cant login and cant get an alert if the credentials are incorrect.
Express wasnt set up correctly and in my app file i had 'header' changed that to 'headers'.
app file
login = () => {
fetch('http://localhost:8080/users/', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Accept': 'application/json',
},
body: JSON.stringify({
"username": this.state.username,
"password": this.state.password,
})
})
.then((response) => response.json())
.then ((res) => {
if (res.success === true) {
AsyncStorage.setItem('user', res.user);
this.props.navigation.navigate('Profile');
}
else {
alert(res.message);
}
})
.done();
}
}
express file App.js
const port = 8080;
var createError = require('http-errors');
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');
var bodyParser = require('body-parser');
var mysql = require('mysql');
var indexRouter = require('./routes/index');
var usersRouter = require('./routes/users');
var app = express();
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use('/', indexRouter);
app.use('/users', usersRouter);
// catch 404 and forward to error handler
app.use(function(req, res, next) {
next(createError(404));
});
// 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');
});
app.listen(port, () => console.log(`Backend now listening on ${port}!`));
module.exports = app;
express users.js
var express = require('express');
var router = express.Router();
var mysql = require('mysql');
var connection = mysql.createConnection({
host: '127.0.0.1',
user: 'root',
password: 'root',
database: 'users',
port: 8889
});
router.post('/', function(req, res) {
var username = req.body.username;
var password = req.body.password;
connection.query(
"SELECT * FROM user WHERE username = ? AND password = ?",
[username, password], function (err, row){
if (err) {
console.log(err);
res.send({ 'success': false, 'message': 'Kan niet met de database verbinden'});
}
if (row.length > 0 ){
res.send({ 'success': true, 'user': row[0].username });
} else {
res.send({ 'success': false, 'message': 'Gebruiker niet gevonden'});
}
});
});
module.exports = router;
Hope this helps for people who are stuck on the same thing.

How can i resolve 'Cannot set headers after they are sent to the client'

How can I resolve Cannot set headers after they are sent to the client:
app.js
var express = require('express');
var session = require('express-session');
var mongoose = require('mongoose');
var app = express();
var ejs = require('ejs');
var port = 3000;
var bodyParser = require('body-parser');
var mongoDB = "mongodb://localhost:27017/vinavdb";
app.set('views', __dirname + '/admin') app.engine('html', ejs.renderFile);
app.set('view engine', 'ejs');
app.set('trust proxy', 1);
app.use(session({
secret: 'dsghbrtdfhbdfg64545TRYFFHGGJNN',
resave: false,
saveUninitialized: true
}))
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
extended: true
}));
var sess;
mongoose.Promise = global.Promise;
mongoose.connect(mongoDB, {
useNewUrlParser: true
});
var nameSchema = new mongoose.Schema({
firstname: String,
lastname: String,
email: String,
password: String
});
var User = mongoose.model("User", nameSchema);
app.get("/", (req, res) => {
sess = req.session;
if (sess.email) {
res.redirect("/admin");
} else {
res.sendFile(__dirname + "/index.html");
}
});
app.get("/login", (req, res) => {
res.sendFile(__dirname + "/login.html");
});
app.post("/addname", function(req, res) {
var myData = new User(req.body);
User.findOne({
email: req.body.email
}, function(err, resv) {
if (resv == null) {
myData.save().then(item => {
res.send("Name saved to database")
}).catch(err => {
res.status(400).send("Unable to save to database");
});
res.send("ThankYou For your Registration")
} else if (resv.email == req.body.email) {
res.send("Email is already registered");
} else {
res.send("Srry data is not allowed");
}
});
});
app.post("/login", function(req, res, next) {
User.findOne({
email: req.body.email
}, function(err, vals) {
if (vals == null) {
res.end("Invalid Logins");
} else if (vals.email == req.body.email && vals.password == req.body.password) {
sess = req.session;
sess.email = req.body.email;
res.redirect('/admin');
} else {
res.send("Srry data is not allowed");
}
});
});
app.route('/admin').get(function(req, res, next) {
sess = req.session;
if (sess.email) {
res.send(__dirname + "/admin/index.html");
} else {
res.write('Please login first.');
}
})
app.listen(port, () => {
console.log("Server listening on port " + port);
});
Cause of your error : You are trying to send a response of a single request twice.
One request have one response.
Once response is send, you cannot send it again for the same request.In your /addname API, You are trying to send response twice. So remove one.
Here .save() is asynchronous function so node will not wait and execute
res.send("ThankYou For your Registration") first and later once record will be saved it will try to send res.send("Name saved to database") so you are getting error here.
app.post("/addname", function(req, res) {
var myData = new User(req.body);
User.findOne({
email: req.body.email
}, function(err, resv) {
if (resv == null) {
myData.save().then(item => {
console.log("Name saved to database")
res.send("ThankYou For your Registration")
}).catch(err => {
res.status(400).send("Unable to save to database");
});
} else if (resv.email == req.body.email) {
res.send("Email is already registered");
} else {
res.send("Srry data is not allowed");
}
});
});
After you execute a res.send you cannot call it again in the same request, it only allows one response per request. In your code, I think in this part it can happens:
if (resv == null) {
myData.save().then(item => {
res.send("Name saved to database")
}).catch(err => {
res.status(400).send("Unable to save to database");
});
res.send("ThankYou For your Registration")
}
In this if, when you are saving myData you are sending a response, but asynchronously you already sent another response previously ("ThankYou For your Registration").
Hope it helps

node server not returning any response after API request

I am building an API with Node.js, Express, MYSQL and with the help of sequelize. I am using MVC pattern.
The problem I am encountering however is the server cannot send back any http response after request. When sending a post request for example with postman, the request keeps on loading and will terminate after around 2 minutes with COULD NOT GET ANY RESPONSE exception. While this is happening, data is correctly saved in the database.
This is my AuthController user registration method:
'use strict';
// AuthController.js
var express = require('express');
var router = express.Router();
var bodyParser = require('body-parser');
router.use(bodyParser.urlencoded({ extended: false }));
router.use(bodyParser.json());
var jwt = require('jsonwebtoken');
var bcrypt = require('bcryptjs');
const Model = require('../models/index');
const User = Model.sequelize.import('../models/user');
// Register new User.
exports.register = function(req, res) {
var hashedPassword = bcrypt.hashSync(req.body.password, 8);
User.create({
name : req.body.name,
email : req.body.email,
password : hashedPassword
},
function (err, user) {
if (err)
{
return res.status(500).send("There was a problem registering the user. "+err)
}
else{
// create a token
var token = jwt.sign({ id: user._id }, process.env.AUTH0_CLIENT_SECRET, {
expiresIn: 86400 // expires in 24 hours
});
res.status(200).json({ auth: true, token: token });
}
});
};
// App.js
var createError = require('http-errors');
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');
const cors = require('cors');
var app = express();
var indexRoutes = require('./routes/index');
var userRoutes = require('./routes/users');
var courseRoutes = require('./routes/courses');
var authRoutes = require('./routes/auth');
// view engine setup
// Currently I am not using view-templates
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');
app.use(cors());
app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(cors()); //enable CORS
app.use(express.static(path.join(__dirname, 'public')));
//User Routes
app.use('/', indexRoutes);
app.use('/api', userRoutes);
app.use('/api', courseRoutes);
app.use('/api/auth', authRoutes);
// catch 404 and forward to error handler
app.use(function(req, res, next) {
next(createError(404));
});
// 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
//auth.js
var express = require('express');
var router = express.Router();
//Require Controller Modules
var controller = require('../controllers/AuthController');
//Register new user
router.post('/register', controller.register);
router.get('/user', controller.me);
router.post('/login', controller.login);
router.get('/logout', controller.logout);
module.exports = router;
//User Model
'use strict';
module.exports = (sequelize, DataTypes) => {
var User = sequelize.define('User', {
//id: DataTypes.INTEGER,
name: DataTypes.STRING,
email: {type: DataTypes.STRING, allowNull: false, unique: true, validate: { isEmail: {msg: "Invalid Email"} }},
password: DataTypes.STRING
}, {});
User.associate = function(models) {
// associations can be defined here
};
return User;
};
DB Connection //in models/index.js
'use strict';
var fs = require('fs');
var path = require('path');
var Sequelize = require('sequelize');
var basename = path.basename(__filename);
var env = process.env.NODE_ENV || 'development';
var config = require(__dirname + '/../config/config.json')[env];
var db = {};
const Op = Sequelize.Op;
if (config.use_env_variable) {
var sequelize = new Sequelize(process.env[config.use_env_variable], config);
} else {
var sequelize = new Sequelize(config.database,
config.username,
config.password,
{
host: config.host,
dialect: config.dialect,
operatorsAliases: false,
}
);
//check if connection is established
sequelize
.authenticate()
.then(() => {
console.log('Database Connection has been established successfully.');
})
.catch(err => {
console.error('Unable to connect to the database:', err);
});
}
fs
.readdirSync(__dirname)
.filter(file => {
return (file.indexOf('.') !== 0) && (file !== basename) && (file.slice(-3) === '.js');
})
.forEach(file => {
var model = sequelize['import'](path.join(__dirname, file));
db[model.name] = model;
});
Object.keys(db).forEach(modelName => {
if (db[modelName].associate) {
db[modelName].associate(db);
}
});
db.sequelize = sequelize;
db.Sequelize = Sequelize;
module.exports = db;
I think there is something wrong I am committing or missing out something. I am experiencing this problem when sending POST REQUESTS. Data is saved in mysql table but no response is sent back.
Please assist. Thanks.
Thank you guys for trying to assist. After working around I discovered that problem was with the controller method. The way it was structured was not sending back response after data is persisted in the database.
This is how I recoded my register method in AuthController:
//Old one
// Register new User.
exports.register = function(req, res) {
var hashedPassword = bcrypt.hashSync(req.body.password, 8);
User.create({
name : req.body.name,
email : req.body.email,
password : hashedPassword
},
function (err, user) {
if (err)
{
return res.status(500).send("There was a problem registering the user. "+err)
}
else{
// create a token
var token = jwt.sign({ id: user._id }, process.env.AUTH0_CLIENT_SECRET, {
expiresIn: 86400 // expires in 24 hours
});
res.status(200).json({ auth: true, token: token });
}
//Rewrite:
// Register new User.
exports.register = function(req, res) {
var hashedPassword = bcrypt.hashSync(req.body.password, 8);
User.create({
name : req.body.name,
email : req.body.email,
password : hashedPassword
})
.then(user=>{
// create a token
var token = jwt.sign({ id: user._id }, config.secret, {
expiresIn: 86400 // expires in 24 hours
});
return res.status(200).json({ auth: true, token: token });
}).catch(err=>{
return res.status(500).send("There was a problem registering the user. "+err)
});
};
This worked for me and the code now works as expected.