Using fetch API to send a post request from two forms when the button add household is clicked the /addcustomer route works but the /add household route just adds null values into the database except for the predefined values of date_created
and userid
. I checked on the client side and the data is being sent properly but it is using the text/html content type even though I specified to use multiform data. Here is the code:
const fileInput = document.getElementById('fileInput');
// Select the label element
const fileInputLabel = document.querySelector('.fileInputLabel');
// Listen for changes in the file input
fileInput.addEventListener('change', function() {
// Get the selected file
const file = fileInput.files[0];
// Check if a file is selected
if (file) {
// Update the label text with the file name
fileInputLabel.textContent = "Uploaded Picture!";
} else {
// If no file is selected, revert to the default label text
fileInputLabel.textContent = 'Uploaded image!';
}
});
document.getElementById('addHousehold').addEventListener('click', function() {
let rightForms = document.querySelectorAll('.right-form');
// Iterate over each right-form
rightForms.forEach((form, index) => {
let formData = new FormData();
// Get data from inputs in the current form
let inputs = form.querySelectorAll('input, select');
inputs.forEach(input => {
if (input.type === 'file') {
// If the input is a file input, append the file to the FormData object
formData.append(input.name, input.files[0]);
} else {
formData.append(input.name, input.value);
}
});
// Log the FormData object
console.log(formData);
// Send the form data to the Express.js API
fetch('/addCustomer', {
method: 'POST',
body: formData,
headers: {
//'Content-Type': 'application/x-www-form-urlencoded'
}
})
.then(response => {
if (!response.ok) {
throw new Error('Network response was not ok');
}
return response.text();
})
.then(formData => {
console.log('Data sent successfully:', formData);
// Optionally, update the UI to reflect the successful submission
})
.catch(error => {
console.error('Error sending data:', error);
// Optionally, update the UI to indicate the error
});
});
});
document.addEventListener('DOMContentLoaded', () => {
const addHouseholdButton = document.getElementById('addHousehold');
addHouseholdButton.addEventListener('click', () => {
const address = document.getElementById('address').value;
const apt = document.getElementById('apt').value;
const workphone = document.getElementById('workphone').value;
const city = document.getElementById('city').value;
const zipcode = document.getElementById('zipcode').value;
const formData_contact = new FormData();
formData_contact.append('address', address);
formData_contact.append('apt', apt);
formData_contact.append('workphone', workphone);
formData_contact.append('city', city);
formData_contact.append('zipcode', zipcode);
fetch('/addhousehold', {
method: 'POST',
body: formData_contact,
headers: {
}
})
.then(response => {
if (!response.ok) {
throw new Error('Network response was not ok');
}
return response.text();
})
.then(formData_contact => {
console.log('Data sent successfully:', formData_contact);
// Optionally, update the UI to reflect the successful submission
})
.catch(error => {
console.error('Error sending data:', error);
// Optionally, update the UI to indicate the error
});
});
});
const express = require('express');
const session = require('express-session');
const mysql = require('mysql');
const app = express();
const port = 5000;
const multer = require('multer');
const upload = multer({ dest: '/public/images/' });
//Allows the user to use public folder to access views
app.use(express.static('public'));
// MySQL connection configuration
const connection = mysql.createConnection({
host: 'localhost',
user: 'root',
password: 'letmein1',
database: 'mydatabase'
});
//View engine
app.set('view engine', 'ejs');
//Middle ware for sessions
app.use(session({
secret: 'mysecret', // Change this to a long random string
resave: false,
saveUninitialized: true
}));
// Connect to the database
connection.connect((err) => {
if (err) {
console.error('Error connecting to MySQL database: ' + err.stack);
return;
}
console.log('Connected to MySQL database as ID ' + connection.threadId);
});
app.use(express.json());
// Middleware to parse the body of incoming requests
app.use(express.urlencoded({ extended: true }));
// Route to handle GET requests to the login page
app.get('/', (req, res) => {
res.render('login', { user: req.session.user });
});
//Post request for login page
app.post('/login', (req, res) => {
const { username, password } = req.body;
connection.query('SELECT * FROM users WHERE TRIM(username) = ? AND TRIM(password) = ?', [username.trim(), password.trim()], (error, results, fields) => {
if (error) {
res.send('Error retrieving user from database');
return;
}
if (results.length > 0) {
req.session.user = results[0];
res.redirect('/dashboard');
} else {
const message = 'Invalid Credentials';
res.render('badLogin', { user: req.session.user });
}
});
});
//Dashboard
app.get('/dashboard', (req, res) => {
// Check if the user is logged in
if (req.session.user) {
// If user is logged in, render the dashboard page
res.render('dashBoard', { user: req.session.user });
} else {
// If user is not logged in, redirect to the login page
res.redirect('/');
}
});
app.get('/logout', (req, res) => {
req.session.user = null;
res.redirect('/');
});
app.get('/login', (req, res) => {
res.render('login', { user: req.session.user });
});
const bodyParser = require('body-parser');
app.use(bodyParser.urlencoded({extended: true}));
app.post('/addCustomer', upload.single('profilePicture'), (req, res) => {
if (!req.session.user || !req.session.user.id) {
res.status(403).send('User not authenticated');
return;
}
const { name, dateOfBirth, relation, Year, Make, Model, VIN, CellPhone, address, apt, workphone, city, zipcode } = req.body;
connection.query('INSERT INTO customers (name, profile_picture, dateOfBirth, relation, year, make, model, vin, cellphone) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)', [name, req.file.filename, dateOfBirth, relation, Year, Make, Model, VIN, CellPhone], (error, results, fields) => {
if (error) {
console.error('Error storing customer data:', error);
res.status(500).send('Error storing customer data');
return;
}
console.log(req.body );
});
});
app.post('/addhousehold', (req, res) => {
// Check if the user is authenticated or any other necessary checks
if (!req.session.user) {
// Handle unauthenticated user
res.status(403).send('User not authenticated');
return;
}
const { address, apt, workphone, city, zipcode } = req.body;
connection.query('INSERT INTO household (address, apt, work_phone, city, zipcode, date_created, userid) VALUES (?, ?, ?, ?, ?, NOW(), ?)', [address, apt, workphone, city, zipcode, req.session.user.id], (householdError, householdResults, householdFields) => {
if (householdError) {
console.error('Error storing household data:', householdError);
res.status(500).send('Error storing household data');
return;
}
console.log(req.body);
console.log('Household data stored successfully');
res.status(200).send('Customer and household data stored successfully');
});
});
/*app.post('/addCustomer', upload.single('profilePicture'), (req, res) => {
const { name, dateOfBirth, relation, Year, Make, Model, VIN, CellPhone } = req.body;
connection.query('INSERT INTO customers (name, profile_picture, dateOfBirth, relation, year, make, model, vin, cellphone) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)', [name, req.file.filename, dateOfBirth, relation, Year, Make, Model, VIN, CellPhone], (error, results, fields) => {
if (error) {
console.error('Error storing customer data:', error);
res.status(500).send('Error storing customer data');
return;
}
console.log('Customer data stored successfully');
res.status(200).send('Customer data stored successfully');
const { address, apt, workPhone, city, zipcode, userId } = req.body;
connection.query('INSERT INTO household (address, apt, work_phone, city, zipcode, date_created, user_id) VALUES (?, ?, ?, ?, ?, NOW(), ?)', [address, apt, workPhone, city, zipcode, userId], (householdError, householdResults, householdFields) => {
if (householdError) {
console.error('Error storing household data:', householdError);
res.status(500).send('Error storing household data');
return;
}
console.log('Household data stored successfully');
res.status(200).send('Customer and household data stored successfully');
});
});
}); */
app.listen(port, () => {
console.log(`Server is running on port ${port}`);
});
I checked to see if the values being entered match the constraints of the attributes in the database so that is not the case.
I also console.log()
-ed the values gather in the fetch API that routes to /addhousehold and it prints the values correctly.
When I try to console.log
the req.body
on the server’s side the only contents I can see is name, date of birth , relation, year, make, model , vin and cellphone. The values relating to household is undefined and not listed so that tells me there is a problem with the way the server is receiving the data. I am thinking that the header is not sending the data in the correct format but every time I try to change the header type it still sends the post request as html/text.