#client isnt sending body data back to server
41 messages · Page 1 of 1 (latest)
controller function:
async function signUpUser(req, email, password, username) {
console.log("Received request body:", req.body);
try {
// hash the password using bcrypt
const hashedPassword = await bcrypt.hash(password, 10);
// create a new user record in the database
const newUser = await User.create({ username, email, password: hashedPassword });
console.log("New User:", newUser.toJSON());
// store user session data (e.g., user ID) once signed up
req.session.userId = newUser.id;
console.log("Session UserId:", req.session.userId);
// log the user info
console.log("User registered:", newUser);
return { success: true };
} catch (error) {
console.error("Error during sign up:", error);
return { error: "Error during sign up" };
}
}```
route handler:
try {
res.render('signUp', { showSignInButton: true });
} catch (error) {
console.error("Failed rendering view:", error);
}
});
// POST request to handle the form submission
router.post('/', async (req, res) => {
const { email, password, username } = req.body;
try {
const result = await signUpUser(req, email, password, username);
if (result.success) {
res.status(200).json({ message: 'User registered successfully' });
res.redirect('/');
} else {
res.status(400).json({ error: result.error });
}
} catch (error) {
console.error('Error in signup route:', error);
res.status(500).json({ error: 'Internal server error' });
}
});```
client script:
const signupForm = document.getElementById('signupForm');
if (signupForm) {
console.log("Signup form found.");
signupForm.addEventListener('submit', function(event) {
event.preventDefault();
const email = document.getElementById('email').value;
const password = document.getElementById('password').value;
const username = document.getElementById('username').value;
console.log("Email:", email);
console.log("Password:", password);
console.log("Username:", username);
fetch('/user/signup', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({ email, password, username }),
})
.then(response => {
console.log("Response received:", response);
if (response.ok) {
return response.json();
} else {
throw new Error('Signup failed');
}
})
.then(data => {
console.log("Signup successful:", data);
window.location.href = '/';
})
.catch(error => {
console.error("Error during signup:", error.message);
});
});
} else {
console.log("Signup form not found");
}
});```
@lucid rampart i already have app.use(express.json()) in my server
darn
don't see anything obvious wrong with client-side (but you should learn async/await)
is my use of async/await bad 😭
router.post('/', async (req, res) => {
const { email, password, username } = req.body;
put a console.log(req.body) here? is it empty?
you aren't using async/await
it replaces .then() and .catch()
ah
i have the console log for req.body directly in my controller function
not in my router
but yeah its empty
j returns:
Received request body: {}
i have async in my controllers j didnt think id need 2 add them directly in my route file
bbut ig that makes sense ty, i'll make some changes
not seeing anything obviously wrong. sure feels like body-parsing isn't happening. what's shown in the network tab of devtools?
this is the console
email: '[email protected]',
password: 'testpassword',
username: 'testuser'
}
Error during sign up: AccessDeniedError [SequelizeAccessDeniedError]: Access denied for user ''@'localhost' (using password: YES)
at ConnectionManager.connect (C:\Users\astro\bootcamp\Gamify-Todo\node_modules\sequelize\lib\dialects\mysql\connection-manager.js:94:17)
at process.processTicksAndRejections (node:internal/process/task_queues:95:5)
at async ConnectionManager._connect (C:\Users\astro\bootcamp\Gamify-Todo\node_modules\sequelize\lib\dialects\abstract\connection-manager.js:222:24)
at async C:\Users\astro\bootcamp\Gamify-Todo\node_modules\sequelize\lib\dialects\abstract\connection-manager.js:174:32
at async ConnectionManager.getConnection (C:\Users\astro\bootcamp\Gamify-Todo\node_modules\sequelize\lib\dialects\abstract\connection-manager.js:197:7)
at async C:\Users\astro\bootcamp\Gamify-Todo\node_modules\sequelize\lib\sequelize.js:305:26
at async MySQLQueryInterface.insert (C:\Users\astro\bootcamp\Gamify-Todo\node_modules\sequelize\lib\dialects\abstract\query-interface.js:308:21)
at async User.save (C:\Users\astro\bootcamp\Gamify-Todo\node_modules\sequelize\lib\model.js:2490:35)
at async User.create (C:\Users\astro\bootcamp\Gamify-Todo\node_modules\sequelize\lib\model.js:1362:12)
at async signUpUser (C:\Users\astro\bootcamp\Gamify-Todo\controllers\userAuth.js:14:21) {
parent: Error: Access denied for user ''@'localhost' (using password: YES)
at Packet.asError (C:\Users\astro\bootcamp\Gamify-Todo\node_modules\mysql2\lib\packets\packet.js:728:17)
at ClientHandshake.execute (C:\Users\astro\bootcamp\Gamify-Todo\node_modules\mysql2\lib\commands\command.js:29:26)
at Connection.handlePacket (C:\Users\astro\bootcamp\Gamify-Todo\node_modules\mysql2\lib\connection.js:481:34)
at PacketParser.onPacket (C:\Users\astro\bootcamp\Gamify-Todo\node_modules\mysql2\lib\connection.js:97:12)
at PacketParser.executeStart (C:\Users\astro\bootcamp\Gamify-Todo\node_modules\mysql2\lib\packet_parser.js:75:16)
at Socket.<anonymous> (C:\Users\astro\bootcamp\Gamify-Todo\node_modules\mysql2\lib\connection.js:104:25)
at Socket.emit (node:events:514:28)
at addChunk (node:internal/streams/readable:343:12)
at readableAddChunk (node:internal/streams/readable:316:9)
at Readable.push (node:internal/streams/readable:253:10) {
code: 'ER_ACCESS_DENIED_ERROR',
errno: 1045,
sqlState: '28000',
sqlMessage: "Access denied for user ''@'localhost' (using password: YES)",
sql: undefined
},
original: Error: Access denied for user ''@'localhost' (using password: YES)
at Packet.asError (C:\Users\astro\bootcamp\Gamify-Todo\node_modules\mysql2\lib\packets\packet.js:728:17)
at ClientHandshake.execute (C:\Users\astro\bootcamp\Gamify-Todo\node_modules\mysql2\lib\commands\command.js:29:26)
at Connection.handlePacket (C:\Users\astro\bootcamp\Gamify-Todo\node_modules\mysql2\lib\connection.js:481:34)
at PacketParser.onPacket (C:\Users\astro\bootcamp\Gamify-Todo\node_modules\mysql2\lib\connection.js:97:12)
at PacketParser.executeStart (C:\Users\astro\bootcamp\Gamify-Todo\node_modules\mysql2\lib\packet_parser.js:75:16)
at Socket.<anonymous> (C:\Users\astro\bootcamp\Gamify-Todo\node_modules\mysql2\lib\connection.js:104:25)
at Socket.emit (node:events:514:28)
at addChunk (node:internal/streams/readable:343:12)
at readableAddChunk (node:internal/streams/readable:316:9)
at Readable.push (node:internal/streams/readable:253:10) {
code: 'ER_ACCESS_DENIED_ERROR',
errno: 1045,
sqlState: '28000',
sqlMessage: "Access denied for user ''@'localhost' (using password: YES)",
sql: undefined
}
}```
error log ^^
wait, you said req.body was empty...
for whatever reason req body wasnt working with postman
tried on the local host site
n ig data came back
req.body is clearly defined here, you're just not logging into your SQL server properly
yeah thats what im figuring
go fix your sequelize config
this is my config.js:
const ENV = process.env.NODE_ENV || 'development';
const config = {
development: {
database: process.env.DB_DEV_NAME,
username: process.env.DB_USERNAME,
password: process.env.DB_PASSWORD,
host: process.env.DB_HOST,
dialect: process.env.DB_DIALECT,
},
test: {
database: process.env.DB_TEST_NAME,
username: process.env.DB_USERNAME,
password: process.env.DB_PASSWORD,
host: process.env.DB_HOST,
dialect: process.env.DB_DIALECT,
},
production: {
use_env_variable: process.env.JAWSDB_URL,
dialect: process.env.DB_DIALECT,
},
};
module.exports = config[ENV];
this is the respective connection.js:
const config = require('./config');
let sequelize;
if (config.production) {
sequelize = new Sequelize( {
use_env_variable: config.use_env_variable,
dialect: config.dialect,
});
} else {
sequelize = new Sequelize({
database: config.database,
username: config.username,
password: config.password,
host: config.host,
dialect: config.dialect,
});
}
module.exports = sequelize;
is it bc my config file isnt a json?
I would guess you didn't set the correct values in your .env file
it looks like it was my .env