When I submit form data from HTML form, all values added to MySQL database appear as Undefined. I console.logged req.body and it is shown correctly.
The HTML form in client is a normal form (Important to say that I don't send multipart/form-data, no "enctype" attribute in HTML). I've been looking all over the internet to figure it out what am I doing wrong. I'd like to know what is the problem.
Here's my backend code:
const express = require('express');
const bodyParser = require('body-parser'); // Required for POST requests to work
const mysql = require('mysql');
const path = require('path');
const cors = require('cors');
const app = express();
const port = 1000;
app.use(bodyParser.json());
app.use(express.static(path.join(__dirname, 'public')));
app.use(express.json());
app.use(cors());
const DB = mysql.createConnection({
host: 'localhost',
user: 'root',
password: '1',
database: 'onlineshop',
});
DB.connect(err => {
if (err) throw err
console.log("Connected to MySQL database")
});
app.use(function (req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
next();
});
app.post('/register', (req, res) => {
let newCustomer = req.body;
let q = `INSERT INTO customers (firstname, lastname, email, password, city, street, role)
VALUES ("${newCustomer.firstname}",
"${newCustomer.lastname}",
"${newCustomer.email}",
"${newCustomer.password}",
"${newCustomer.city}",
"${newCustomer.address}",
0`
const result = DB.query(q, (err,result)=>{
if (err) throw err
res.json(result)
})
});
app.listen(port, console.log('App listening at port 1000'));
Thank you!
Is your POST from an HTML form?
If so you need the urlencoded body parser, and you only have the json one. The payload for POSTs from HTML forms is in the urlencoded format. (You can see it in the Network tab of devtools if you're curious.)
const bodyParser = require( 'body-parser' )
app.use( bodyParser.json() )
app.use( bodyParser.urlencoded( { extended: true } ) ) /* add this line */
Related
I am trying to view the body of a POST request and also set some headers. Specifically, I need to allow localhost -> localhost communication, which means adding Access-Control-Allow-Origin: * as a header.
My code so far is:
const express = require("express");
const app = express();
const port = 8080;
app.use(express.json());
app.use((req, res, next) => {
res.setHeader("Access-Control-Allow-Origin", "*");
res.header(
"Access-Control-Allow-Headers",
"Origin, X-Requested-With, Content-Type, Accept"
);
res.sendStatus(200);
next();
});
app.post('/', function (req, res) {
console.log(req.body.name)
res.end();
});
app.listen(port, () => console.log(`Listening on port ${port}`));
When I run the server I get Cannot set headers after they are sent to the client.
How can I combine both app.use()s?
I've tried changing the order of the calls but that doesn't work.
I figured out a way after I posted the question, so I'm sharing it here for anyone else:
const express = require("express");
const app = express();
const port = 8080;
app.use(function( req, res, next ) {
res.setHeader("Access-Control-Allow-Origin", "*");
res.header(
"Access-Control-Allow-Headers",
"Content-Type"
);
res.sendStatus(200);
let data = "";
req.on("data", function( chunk ) {
data += chunk;
console.log(data);
next();
});
});
app.listen(port, () => console.log(`Listening on port ${port}`));
Do you know why I can not manually add the value "Sasan" to mySQL server?
MarioDB is installed in PHPStorm and schema is correctly selcted.
const express = require("express");
const app = express();
const bodyParser = require("body-parser");
const mysql = require("mysql");
const cors = require("cors");
const db = mysql.createPool({
host: "localhost",
user: "root",
password: "Test123456",
database: "shoppingList-DB"
});
app.use(cors());
app.use(express.json());
app.use(bodyParser.urlencoded({extended: true}));
app.get("/test", (req, res) => {
const sqlInsert = "INSERT INTO shoppingList (itemList) VALUES ('Sasan')";
db.query(sqlInsert, (error, result) => {
console.log("error", error);
console.log("result", result)
res.send("Hello Express");
})
})
app.listen(5001, () =>{
console.log("Server is up - Port 5001");
})
The error is pretty clear Access denied for user 'root'#'localhost'. Check your credentials and user access in mysql.user table.
i have problem with post method in mysql node js, when i post the request in postman it return an old record i don't know where come from.
in the first i used Get method and it worked very well but when i changed the method to Post i found thid problem.
i use this request for a form in react app i think the problem is not in the form because i tried the request in postman before try it in the app.
const express = require('express');
const cors = require('cors');
const mysql = require('mysql');
const bodyParser = require('body-parser')
const app = express();
// Connection Mysql
const selectQuery = 'SELECT * FROM userstab';
const connection = mysql.createConnection({
host : 'localhost',
user : 'root',
password : '',
database : 'nodeusers',
});
connection.connect(err => {
if (err) {
return err;
}
});
console.log(connection);
// Connection Express Body-Parser Cors
app.use(cors());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
app.get('/', (req, res) => {
res.send('Hello from the products server')
});
app.post('/userss/add', (req, res) => {
const nom = req.body.nom;
const prenom = req.body.prenom;
const adresse = req.body.adresse;
const email = req.body.email;
console.log(nom, prenom);
const insertQuery = `INSERT INTO userstab (nom, prenom, adresse,
email) VALUES
("${nom}","${prenom}","${adresse}",
"${email}")`;
connection.query(insertQuery,[nom,prenom,adresse,email],
(err,results) => {
if(err) {
res.send(err)
}
console.log(nom, prenom);
res.send({ error: false, data: results, message: 'user has
been added successfully.' });
})
});
// First Get request/////////////////////////////////////////
app.get('/userss/add', (req, res) => {
const { nom, prenom, adresse, email } = req.query;
const insertQuery = `INSERT INTO userstab (nom, prenom, adresse, email) VALUES ('${nom}','${prenom}','${adresse}','${email}')`;
connection.query(insertQuery, (err, results) => {
if(err) {
return res.send(err)
}
else {
return res.send('successfully added user')
}
});
});
////////////////////////////////////////////////////////////////////
app.listen(4000, () => {
console.log('Users server worked on port 4000...')
});
Because you are using users table in post request , and another table called userstab in get request.
So please change you query in post request to be the same table in get request.
I got the codes from a tutorial, seems to work fine until I made routers since I'm trying to create an E-commerce website with a login system.
This is my index.js code
const express = require('express');
const app = express();
const prodRouter = require('./server/routes/prodRouter');
const loginRouter = require('./server/routes/loginRouter');
const regRouter = require('./server/routes/regRouter');
const contRouter = require('./server/routes/contRouter');
const checkRouter = require('./server/routes/checkRouter');
const profRouter = require('./server/routes/profRouter');
const path = require('path'); const port = 3500;
app.use(express.static('public'));
app.set('views', path.join(__dirname, 'server/views'));
app.set('viewengine', 'pug');
app.use('/prod', prodRouter);
app.use('/login',loginRouter);
app.use('/reg', regRouter);
app.use('/cont',contRouter);
app.use('/check', checkRouter);
app.use('/profile',profRouter);
app.get('/', (req, res) =>{res.render('Home.pug', {}); });
app.listen(port, (err) => { // arrow function feature from ES6 if(err){ console.log(err); }
console.log(`Listening to port ${port}!`); });
and loginRouter.js
const express = require('express'); const router = express.Router();
const app = express();
const mysql = require('mysql');
const server = require('http').createServer(app);
bodyParser = require('body-parser');
const connection = mysql.createConnection({
host: 'localhost',
database: 'login',
user: 'root',
password: '',
});
users = []; connections = [];
router.get('/', (req, res) => {
res.render('login', {});
});
app.use(bodyParser.urlencoded({
extended: true
});
app.use(bodyParser.json());
connection.connect();
app.post('/', function(req, res){
var email= req.body.email;
var password = req.body.password;
connection.query('SELECT * FROM user WHERE email = ?',[email],function (error, results, fields) {
if (error) {
// console.log("error ocurred",error);
res.send({
"code":400,
"failed":"error ocurred"
})
}else{
// console.log('The solution is: ', results);
if(results.length >0){
if([0].password == password){
return res.redirect('/profile');
}else{
res.send({
"code":204,
"success":"Email and password does not match"
});
}
}else{
res.send({
"code":204,
"success":"Email does not exits"
});
}
}
});
enter code here
});
module.exports = router;
my pug form:
form#login-form(method='post')
fieldset.input
p#login-form-username
label(for='modlgn_username') Email
input#modlgn_username.inputbox(type='text', name='email', size='18', required)
p#login-form-password
label(for='modlgn_passwd') Password
input#modlgn_passwd.inputbox(type='text', name='password', size='18', required)
.remember
p#login-form-remember
label(for='modlgn_remember')
a(href='#') Forget Your Password ?
input.button(type='submit', value='Sign In')
I'm pretty sure I did something wrong with the router, because every time I login, I keep getting CANNOT POST instead of going to the profile page.
Any help would be greatly appreciated.
EDIT: I added my pug code for form.
EDIT: the problem only occurs if the login page is not the main page.
example:
login page > *logs in > profile - no problem
home page > login page > *logs in > profile - error
This is happening because you don't have an action on your form (see this article for details). When you don't have an action the form is submitted to the URL it lives at, so if you POST on your home page without an action the post will go to /home.
Change the form element to look like this:
form#login-form(method='post' action='/login')
I am building a rest api with node.js and mysql. But in my GET I am getting a error of "could not get any response" with router.get that uses the mysql.
Here is my code, mt it helps.
server.js
const http = require('http');
const app = require('./app');
const port = process.env.PORT || 3000;
const server = http.createServer(app);
server.listen(port);
app.js
const express = require('express');
const app = express();
const userRoutes = require('./api/routes/user');
var mysql = require("mysql");
//Database connection
app.use(function(req, res, next){
res.locals.connection = mysql.createConnection({
host : 'localhost',
user : 'root',
password : ' ',
database : 'achai_db'
});
res.locals.connection.connect();
next();
});
user.js
const express = require('express');
const router = express.Router();
router.get('/', function(req, res, next) {
res.locals.connection.query('SELECT * from users', function (error, results, fields) {
if (error) throw error;
res.send(JSON.stringify({"status": 200, "error": null, "response": results}));
});
});
module.exports = router;
In that user.js if i use a get without using the mysql the connection works.
You need to understand JavaScript nature(Asynchronous programming) and you must not open mysql connection in each request, you can use connection pooling and keep connection open, just acquire connection and release it after query.
updated app.js
const express = require('express');
const app = express();
const userRoutes = require('./api/routes/user');
const mysql = require('mysql');
//Database connection
const pool = mysql.createPool({
host : 'localhost',
user : 'root',
password : ' ',
database : 'achai_db'
});
app.use(function(req, res, next){
pool.getConnection(function(err, connection) {
res.locals.connection = connection;
next(err);
});
});
updated user.js
const express = require('express');
const router = express.Router();
router.get('/', function(req, res, next) {
res.locals.connection.query('SELECT * from users', function (error, results, fields) {
res.locals.connection.release();
if (error) throw error;
//res.json({"status": 200, "error": null, "response": results});
res.send(JSON.stringify({"status": 200, "error": null, "response": results}));
});
});
module.exports = router;