I am unable to Post data from postman to mysql database
I'm using express
I have tried using Body and Raw x-wwww-form-urlencoded
Here is my code (Yes everything is in the same file I know it's not a good thing I'm sorry)
var app = express();
var bodyParser = require('body-parser');
var mysql = require('mysql');
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
// default route
app.get('/', function (req, res) {
return res.send({ error: true, message: 'hello' })
});
// connection configurations
var dbConn = mysql.createConnection({
host: 'localhost',
user: 'root',
password: '',
database: 'testexpress'
});
// connect to database
dbConn.connect();
// Add a new user
app.post('/user', function (req, res) {
let user = req.body.user;
if (!user) {
return res.status(400).send({ error:true, message: 'Please provide user' });
}
dbConn.query("INSERT INTO users SET ? ", { user: user }, function (error, results, fields) {
if (error) throw error;
return res.send({ error: false, data: results, message: 'New user has been created successfully.' });
});
});
// set port
app.listen(3000, function () {
console.log('Node app is running on port 3000');
});
module.exports = app;
here is my screenshot error from Postman and my database
Modify your code like this. It should work
// Add a new user
app.post('/user', function (req, res) {
let user = [req.body]
console.log(user);
if (!user) {
return res.status(400).send({ error:true, message: 'Please provide user' });
}
dbConn.query("INSERT INTO users SET ? ", user, function (error, results, fields) {
if (error) throw error;
return res.send({ error: false, data: results, message: 'New user has been created successfully.' });
});
});
Your code is showing this error message error:true, message: 'Please provide user because everytime in your code the condition if (!user) is executed, because let user = req.body.user is going to give undefined value so you are going to get that error and the rest of the code will never execute then
.
Related
I am working to implement passport.js in my react/node/express/sequelize app.
I currently have middleware working for logging a user in, and checking if the user is authenticated. However, when a new user signs up or registers, their user data is not being saved to the server session (even though it is created in the DB). This means after a user registers, they have to go to the login page, enter their credentials and hit login before their session is saved.
My login function is simple:
router.post('/login', passport.authenticate('local'), (req, res) => {
//console.log(req);
console.log("Is authenticated: " + req.isAuthenticated());
res.json(req.user);
});
it uses passport.authenticate local strategy, which I've defined as:
passport.use(new LocalStrategy(
{
usernameField: 'email',
},
((email, password, done) => {
User.findOne({
where: {
email,
},
}).then((dbUser) => {
if (!dbUser) {
return done(null, false, {
message: 'Incorrect email.',
});
}
if (!dbUser.validPassword(password)) {
return done(null, false, {
message: 'Incorrect password.',
});
}
return done(null, dbUser);
});
}),
));
I know from the passport documentation and from looking at other questions that the passport.authenticate local strategy automatically calls the req.login() function, which serializes my user information and saves it in the server session.
My main issue is I'm not sure exactly how to implement this during my register function.
router.post('/signup', (req, res) => {
const user = {
first_name: req.body.first_name,
last_name: req.body.last_name,
email: req.body.email,
password: req.body.password,
};
User.findOrCreate({where: {email: user.email}, defaults: user})
.then(data => {
res.send(data);
})
.catch(err => {
res.status(500).send({
message:
err.message || "Some error occurred while creating the User."
});
});
});
I've tried calling req.login() after findOrCreate, but I get an error:
(node:42313) UnhandledPromiseRejectionWarning: Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client
If I use my local strategy, I get an unauthorized response (since the credentials I'm using to authorize are not yet in the DB).
I figure I need to make a custom strategy for sign in, but it's not clear to me if that's the right approach, or how I would specify it.
I fixed this by adding req.login before res.send:
router.post('/signup', (req, res) => {
const user = {
first_name: req.body.first_name,
last_name: req.body.last_name,
email: req.body.email,
password: req.body.password,
};
User.findOrCreate({where: {email: user.email}, defaults: user})
.then(data => {
req.login(data[0], function(err) {
if (err) {
console.log("login function erroring out with: " + err)
}
});
res.send(data);
})
.catch(err => {
res.status(500).send({
message:
err.message || "Some error occurred while creating the User."
});
});
});
I have a simple Azure function trying to get all data from a SQL table. The connection is successful and I can connect to the database, but whenever I run the get request, I end up with an error
Exception: TypeError: connection.query is not a function
Stack: TypeError: connection.query is not a function
This is the line throwing the error
connection.query(query, (err, results, fields) => {
this is my index.js azure get function
const express = require('express')
const bodyParser = require('body-parser')
let connection = require('../configs/dbConfig')
const app = express()
app.use(bodyParser.json())
app.use(bodyParser.urlencoded({ extended: true }))
module.exports = async function (context, req, res) {
const query = 'SELECT * FROM entrys'
connection.query(query, (err, results, fields) => {
if (err) {
const response = { data: null, message: err.message, }
res.send(response)
}
const pokemons = [...results]
const response = {
data: pokemons,
message: 'All entrys successfully retrieved.',
}
res.send(response)
})
}
Am using tedious as the connection driver. my dbconfig
let Connection = require('tedious').Connection;
let pool = {
server: "localhost", // or "localhost"
authentication: {
type: "default",
options: {
userName: "sa",
password: "root",
}
},
options: {
database: "testing",
encrypt: false
}
};
var connection = new Connection(pool);
connection.on('connect',function(err){
if(err){
console.log('Connection Failed');
throw err;
}
else{
console.log('Connected');
}
});
module.exports = connection
what am I doing wrong, thank you in advance
You should use Request to query.
In the official documentation, I did not see the usage of connection.query. It is not recommended that you use tedious when you are not very familiar with it. I have a sample code here, I hope it helps you.
You can download my Sample Code which use mssql package.
var express = require('express');
var router = express.Router();
let connection = require('../configs/dbConfig')
var Request = require('tedious').Request;
/* GET users listing. */
router.get('/', function(req, res, next) {
request = new Request("select 42, 'hello world'", function(err, rowCount) {
if (err) {
console.log(err);
} else {
console.log(rowCount + ' rows');
}
});
request.on('row', function(columns) {
columns.forEach(function(column) {
console.log(column.value);
});
});
connection.execSql(request);
res.send('respond with a resource');
});
module.exports = router;
Test Result:
app.post("/login", async (req, res) => {
// Destructure Req Body
const { email, password } = req.body;
// Validate Body
if (!email || !password) {
res.status(400).json({ success: false, message: "PARAMS_MISSING" });
}
// Build the SQL query
const query = `SELECT * FROM user WHERE email = "${email}"`;
// Get the user from DB
const user = await db(query);
// Check if password is valid
const isPasswordValid = decryptPassword(user.hash_password, password);
// Return if password is not valid
if (!isPasswordValid) {
res.status(401).json({ success: false, message: "INAVLID_PASSWORD" });
}
// Generate Token
const token = generateToken({ id: user.id, email: user.email });
// Save Cookie
res.cookie("token", token, { maxAge: 900000, httpOnly: true });
res.end();
// Return
res.json({ success: true, message: "USER_AUTHENTICATED" });
});
UnhandledPromiseRejectionWarning: Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client
I m getting this error again n again idk what to do i m beginner,
I'm facing this weird issue in NodeJS when using with Passport.js, Express. Basically, I get an error saying "Cannot set headers after they are sent to the client" even though I don't send more than one header.
This error means the 'res' object respond twice. E.g: in your '// Validate body' if the password or email are missing your http connection respond 'res.status().json().'(note that is closing the http connection), but as you didn't stop the execution of the code, it carries on then it may respond a second time in the // Return if password is not valid which create the err as the header can not be set twice and the connection is already close.
Than more here you error is Unhandled, as an Async function reject, the error must be handle, wrapping the code in a try{} catch(e){} will fix it.
So that should fix your issues
app.post("/login", async (req, res) => {
try{
// Destructure Req Body
const { email, password } = req.body;
// Validate Body
if (!email || !password) {
res.status(400).json({ success: false, message: "PARAMS_MISSING" });
return // stop execution of the function
}
// Build the SQL query
const query = `SELECT * FROM user WHERE email = "${email}"`;
// Get the user from DB
const user = await db(query);
// Check if password is valid
const isPasswordValid = decryptPassword(user.hash_password, password);
// Return if password is not valid
if (!isPasswordValid) {
res.status(401).json({ success: false, message: "INAVLID_PASSWORD" });
return // stop exec of the function
}
// Generate Token
const token = generateToken({ id: user.id, email: user.email });
// Save Cookie
res.cookie("token", token, { maxAge: 900000, httpOnly: true });
res.end();
// Return
res.json({ success: true, message: "USER_AUTHENTICATED" });
} catch(err) {
console.error(err) // code to handle the err
}
});
But still, a problem remain as at the end of your script, you have a res.end()(which terminate the connection) and right after a res.json() which will fail as the connection has been close the line before (than more the statusCode is missing)
I want to get the data from my server and show it in reactjs. I think that my error is in the client side. I'm getting the data from a API and i know that the data calling works but i'm not expert using fetch and i'm learning.
this is my server
const express = require('express');
const app = express();
const bodyParser = require('body-parser');
const mysql = require('mysql');
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
extended: true
}));
// connection configurations
const mc = mysql.createConnection({
host: 'localhost',
user: 'root',
password: '12345',
database: 'node_task_demo',
//socketPath: '/Applications/MAMP/tmp/mysql/mysql.sock'
});
// connect to database
mc.connect();
// default route
app.get('/', function (req, res) {
return res.send({ error: true, message: 'hello' })
});
// Here where I'm calling in the client side
app.get('/todos', function (req, res) {
mc.query('SELECT * FROM tasks', function (error, results, fields) {
if (error) throw error;
return res.send({ error: false, data: results, message: 'Todo list' });
});
});
// Search for todos with ‘bug’ in their name
app.get('/todos/search/:keyword', function (req, res) {
var mensaje = 'Todos search list.';
let keyword = req.params.keyword;
mc.query("SELECT * FROM tasks WHERE task LIKE ? ", ['%' + keyword + '%'], function (error, results, fields) {
if (error) throw error;
return res.send({ error: false, data: results, message: mensaje});
});
});
// Retrieve todo with id
app.get('/todo/:id', function (req, res) {
let task_id = req.params.id;
if (!task_id) {
return res.status(400).send({ error: true, message: 'Please provide task_id' });
}
mc.query('SELECT * FROM tasks where id=?', task_id, function (error, results, fields) {
if (error) throw error;
return res.send({ error: false, data: results[0], message: 'Todos list.' });
});
});
// Add a new todo
app.post('/todo', function (req, res) {
let task = req.body.task;
if (!task) {
return res.status(400).send({ error:true, message: 'Please provide task' });
}
mc.query("INSERT INTO tasks SET ? ", { task: task }, function (error, results, fields) {
if (error) throw error;
return res.send({ error: false, data: results, message: 'New task has been created successfully.' });
});
});
// Update todo with id
app.put('/todo', function (req, res) {
let task_id = req.body.task_id;
let task = req.body.task;
if (!task_id || !task) {
return res.status(400).send({ error: task, message: 'Please provide task and task_id' });
}
mc.query("UPDATE tasks SET task = ? WHERE id = ?", [task, task_id], function (error, results, fields) {
if (error) throw error;
return res.send({ error: false, data: results, message: 'Task has been updated successfully.' });
});
});
// Delete todo
app.delete('/todo', function (req, res) {
let task_id = req.body.task_id;
if (!task_id) {
return res.status(400).send({ error: true, message: 'Please provide task_id' });
}
mc.query('DELETE FROM tasks WHERE id = ?', [task_id], function (error, results, fields) {
if (error) throw error;
return res.send({ error: false, data: results, message: 'Task has been updated successfully.' });
});
});
// all other requests redirect to 404
app.all("*", function (req, res, next) {
return res.send('page not found');
next();
});
// port must be set to 8080 because incoming http requests are routed from port 80 to port 8080
app.listen(8081, function () {
console.log('Escuchando por el puerto 8081');
});
// allows "grunt dev" to create a development server with livereload
module.exports = app;
This is my client
import React, { Component } from 'react';
import logo from './logo.svg';
import './App.css';
class App extends Component {
constructor(props) {
super(props);
this.state = {
data: []
}
}
componentDidMount() {
return fetch('/todos')
.then((response) => response.json())
.then((responseJson) =>{
this.setState({
data: responseJson.data
});
})
}
render() {
return (
<div className="App">
<div className="App-header">
<img src={logo} className="App-logo" alt="logo" />
<h2>Welcome to React</h2>
</div>
<p className="App-intro">
Este es el resultado de la consulta = <b>{this.state.data}</b>
</p>
</div>
);
}
}
export default App;
React will only render JSX or strings. Unless this.state.data is a string, you will need to transform it into something React render.
You can test this by stringifying your data:
<p className="App-intro">
Este es el resultado de la consulta = <b>{JSON.stringify(this.state.data)}</b>
</p>
If this.state.data is a array, you will need to map it to JSX elements.
I'm making a webapp that uses Socket.io to pass information between the server and the client, one example being login information. The documentation for passport.authenticate says to use it like so:
app.post('/login', passport.authenticate('local', { successRedirect: '/',
failureRedirect: '/login' }));
However, my webapp is using Polymer client-side routing, so the only route my index.js has is this:
app.get('*', function (req, res) {
res.sendFile('./public/index.html', {root: '.'});
});
Instead, I'd like to do something like this:
io.on('connection', function(socket){
socket.on('login', function(data){
passport.authenticate('local', data);
});
});
However, this doesn't work as the authenticate function doesn't even get called right now. Is there a way to make passport work in such a scenario?
You can try something like below .
In your routes define and require the socket module, so you have access to use it in routes.
var express = require('express');
var app = express();
var server = http.createServer(app);
var io = require('socket.io').listen(server);
var router = express.Router();
var passport = require('passport');
io.on('connection', function(socket){
socket.on('login', function(data){
// call the routes
router.post('/login', function(request, response, next) {
passport.authenticate('local', function(err, user, info) {
if (err) {
// return next(err);
socket.emit('loginResult', { success: false });
}
if (!user) {
var message = "Invalid credentials";
socket.emit('loginResult', { success: false , message: message});
}
request.logIn(user, function (err) {
if (err) {
socket.emit('loginResult', { success: false });
}
// if want to save user in session
request.session.user = user;
// after success code
socket.emit('loginResult', { success: true , user : user});
});
})(request, response, next);
});
});
});
Hope this helps.
You can define your custom callback with passport.authenticate(). I have given a example below, you might wanna try that. Go here for more info.
io.on('connection', function(socket){
socket.on('login', function(data){
var req = {}
req.body = data
passport.authenticate('local', function(err, user, info) {
if (err) {
socket.emit('login', { success: false });
}
if (!user) {
socket.emit('login', { success: false });
}
// Set session
req.logIn(user, function(err) {
if (err) {
socket.emit('login', { success: false });
}
socket.emit('login', { success: true });
});
});
});
Update: Problem with previous code was, when using custom callbacks in passport authenticate it uses req object from the closure, which in this case was undefined as it was not in the router. I think, now that you can provide enough authentication data through req.body it should work.