I am working with node, sequelize, migration and mysql. I have already donde the sequelize init and define my models in the file of 'models'. I am testing my first endpoint in the server.js file but when I want run the post it appear the next message :
"Cannot read property 'create' of undefined"
I have read a lot of issues and it is suposed that with the next require y can access my model.
const User = require('./models').User
const express = require('express');
const bodyParser = require('body-parser');
const User = require('./models').User;
const app = express();
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.post('/new', function(req, res){
User.create({
....
}).then((user) => {
....
})}
app.listen(8000)
Related
I was making one app with frontend react.js uses axios to api call and for backend i am using express and node with database mysql while making call to api url i am getting error for access denied error
Error: ER_ACCESS_DENIED_ERROR: Access denied for user ''#'localhost' (using password: NO)
If this is not the case i will be getting axios network error
Axios Network error
i dont know which port to use if i use 3306 port it is already in use. Please take a look at code and suggest about optimization and a better way...
thank you....
config.js will be saving confiq for the connection db
config.js
const config = {
db: {
host: "localhost",
user: "new_user",
password: "password",
database: "db",
},
};
module.exports = config;
db.js will create the connection
db.js
const mysql = require("mysql");
const config = require("./config");
var con = mysql.createPool(config);
module.exports = con;
this is where the express and app server is supposed to create
index.js
const express = require("express");
var mysql = require("mysql");
const cors = require("cors");
const app = express();
app.use(express());
app.use(cors());
const TablesRoutes = require("./routes/TablesRoutes");
//routes
app.use("/", TablesRoutes);
app.listen(8000, () => {
console.log("Running on port :8000");
});
api routes to call from frontend
routes
const express = require("express");
const {
postTableDes,
alterTable,
showTables,
} = require("../Controllers/Tables");
const tablerouter = express.Router();
tablerouter.get("/", showTables);
tablerouter.post("/", postTableDes);
module.exports= tablerouter;
where showing the table act
controller
const con = require("../Config/db");
//get tables
const showTables = async (req, res) => {
//try {
var sql = `show tables`;
const data = await con.query(sql, (err, res)=>{
if(err){
console.log(err);
res.status(404).json({ error: "No show table" });
return;
}
console.log(res);
res.status(202).json(data);
});
module.exports = showTables;
Try to change the config.js to (the createPool call does not expect an object with db property):
const config = {
host: "localhost",
user: "new_user",
password: "password",
database: "db",
};
module.exports = config;
I am currently working on the API of a React.js project. I have no trouble running SQL requests with databases on MySql servers using Express as long as the SQL request only implies a single database.
My problem: I now have to run an SQL request which implies using data from several databases and I do not know how to do it.
What I currently do in my server.js file to run SQL on a single database:
...
const express = require('express');
const cors = require('cors');
const bodyParser = require('body-parser');
const mysql = require('mysql');
...
let sql = "";
...
// *************************
// CLIENT & DB CONFIGURATION
// *************************
const app = express();
app.use(bodyParser.json()); // to support JSON-encoded bodies
app.use(bodyParser.urlencoded({ // to support URL-encoded bodies
extended: true
}));
var server = app.listen(3001, "127.0.0.1", function () {
var host = server.address().address
var port = server.address().port
console.log("Example app listening at http://%s:%s", host, port)
});
app.use(cors());
const connection = mysql.createConnection({
host : 'myhost.fr',
user : 'someone',
password : 'aZefdt%',
database : 'SuiviTruc',
multipleStatements : true
});
connection.connect(function(err) {
if (err) throw err
console.log('You are now connected with SuiviTruc database...')
});
// **************
// Request sample
// **************
app.get('/SelectAffaire_',(req, res) => {
let sql=`SELECT * FROM t_Affaire_;`
connection.query(sql, (error, result)=> {
if (error) throw error;
res.send(result);
})
})
Thanks for your help!
I have a React app + Express server deployed on netlify here. I have a simple api endpoint that queries my MySql DB on AWS.
When I make the api request I am given a "Failed to load resource: the server responded with a status of 502".
If I just return a simple
res.send("simple response")
then everything works fine and I get the response on the client. Could someone point me in the right direction on what I should be looking for?
I've tried to disable the skip_name_resolve parameter on my db to see if the hostname mattered, opening up access to all ports / ip's on the aws security group, look up common examples of express + mysql server implementations, lookup the netlify function docs, and using async await in the server.
// client.jsx
useEffect( () => {
fetch("/.netlify/functions/server/api/getSalesData")
.then(res => res.json())
.then(res => console.log(res));
// server.js
const express = require("express");
const bodyParser = require("body-parser");
const serverless = require('serverless-http');
const mysql = require("mysql");
const db = mysql.createConnection({ ... });
db.connect(function(err) {
if (err) throw err;
console.log('You are now connected...')
});
const app = express();
const router = express.Router();
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
router.get("/api/getSalesData", (req, res) => {
// res.send({ express: "Hello from express" });
db.query("SELECT * FROM Sales LIMIT 5", (err, rows) => {
if (err) throw err;
res.send(rows);
});
});
app.use('/.netlify/functions/server', router);
module.exports = app;
module.exports.handler = serverless(app);
I'm writing a script that runs an Express server with graphql. I m using ES5.
Here is my server.js code (to run the Express server) :
const express = require('express');
const cors = require('cors');
const bodyParser = require('body-parser');
const {graphqlExpress, graphiqlExpress} = require('apollo-server-express');
const schemaTest = require('./schemas/schema');
const app = express();
app.listen(4000, () => { console.log("Listening on 4000")});
app.use('/graphql', bodyParser.json(), graphqlExpress({schemaTest}));
app.use('/graphiql', graphiqlExpress({endpointURL: '/graphql'}));
and here is the code of my schema.js
const {makeExecutableSchema, addMockFunctionsToSchema} = require('graphql-tools');
const typeDefs = `type Query {
greeting: String
}
`;
const schema = makeExecutableSchema({typeDefs});
addMockFunctionsToSchema({ schema });
module.exports = schema;
however i'm getting this isse :
Error: Expected undefined to be a GraphQL schema.
and I m not able to find where is my error.
For your informtion, if I copy paste my schema.js code into the server.js file it works correctly, it is like I m not importing (or exporting) the schema file correctly.
Where is my error
graphqlExpress is expecting a configuration object to be passed to it, with one of the properties on that object being schema. So your code should look something like this:
app.use('/graphql', bodyParser.json(), graphqlExpress({
schema: schemaTest,
}));
What you are currently doing is passing in an object with a schemaTest property, but no schema property.
I am currently using MySQL for the db instead of the popular mongodb, since that is the case there isn't much documentation out there as far as architecture and getting set up. This is my current structure
client
-- angular files
routes
-- index.js
views
-- 404 page
app.js
I don't understand how I can implement controllers or models into this structure. I'm currently grabbing data from the db or sending it with the routes..I'm not sure what the added layer of controllers would do. Maybe this is a dumb question but I would just like to have a clear baseline so that my project will scale well. I feel like there should be way more to this than what I currently have.
index.js
const express = require('express');
const mysql = require('mysql');
const router = express.Router();
const db = mysql.createConnection({
host : 'localhost',
user : 'root',
password : 'password',
database : 'db'
});
// Connect
db.connect((err) => {
if(err){
throw err;
}
console.log('MySql Connected...');
});
// Select Data
router.get('/getData', (req, res) => {
let sql = 'SELECT * FROM data';
let query = db.query(sql, (err, results) => {
if(err) throw err;
console.log(results);
res.send(results)
});
});
module.exports = router;
app.js
const express = require('express');
const mysql = require('mysql');
const bodyParser = require('body-parser');
const path = require('path');
const cors = require('cors');
const compression = require('compression');
const helmet = require('helmet')
const expressSanitizer = require('express-sanitizer');
const index = require('./routes/index');
const app = express();
const port = 3000;
var corsOptions = {
origin: 'http://localhost:8100',
optionsSuccessStatus: 200 // some legacy browsers (IE11, various SmartTVs) choke on 204
}
// var logger = (req, res, next) => {
// console.log('logging...')
// next();
// }
//added security
app.use(helmet())
// //set logger
// app.use(logger)
//cors options
app.use(cors(corsOptions))
//body parser middleware
app.use(bodyParser.json())
app.use(bodyParser.urlencoded({extended: false}))
// Mount express-sanitizer here
app.use(expressSanitizer()); // this line follows bodyParser() instantiations
//set static path
app.use(express.static(path.join(__dirname, 'client')));
// set our default template engine to "ejs"
// which prevents the need for using file extensions
app.set('view engine', 'ejs');
//gzip compression
app.use(compression())
//set views for error and 404 pages
app.set('views', path.join(__dirname, 'views'));
app.use('/', index);
app.use('/fp/trips', trips);
app.listen(port, () => {
console.log('server started on port 3000')
})
When working on Node apps I tend to favor a scheme where controllers are (almost) services -- I think it works really well for small applications.
This is an example:
index.js
let app = express()
let users = require('./services/users')
app.get('/users/:id', async function(req, res, next) => {
try {
res.json(users.getByid(req.params.id))
} catch() {
next(err)
}
})
app.listen(8080)
services/users.js
let db = require('./db')
async function getById(id) {
let conn = await db.connect()
let user = conn.query('SELECT * FROM user WHERE id = ?', [id])
if (!user) {
throw new Error("404")
}
return user
}
module.exports = {getById}
services/db.js
let realDb = require('some-open-source-library-to-interact-with-db')
realDb.initialize(process.env.DB_CREDENTIALS) // pseudo-code here
module.exports = realDb
This though, won't work well when you're building large, complex apps -- I think you will require more structure in that case.
PS: I wouldn't suggest to build a large, complex app ever -- split it into smaller ones where patterns like the one I presented work nicely.
You can use Sequelize as ORM (Object Relational Mapper) for your MySQL DB to make your code more readable and to allow you to create better structure of your app. It also has support for PostgreSQL, MySQL, MariaDB, SQLite, and MSSQL.
There are samples out there how to integrate Sequelize with Express. I'm not sure if I'm allowed to post a github repository here but here it is:
https://github.com/jpotts18/mean-stack-relational
PS. I don't own this repository but this might help you somehow.