form project form scratch full backend-frontend(fullStack)

1. npm init
2. npm install express
3. npm install pg //for postgrace
4. npm install dotenv
5. npm install cors




const express = require('express');
const pg = require('pg');
const { Pool } = require('pg');
require('dotenv').config();
const cors = require('cors')

const app = express(); //this is our app or interface of express
const port = 8080; // Adjust port number as needed

const pool = new pg.Pool({
connectionString: process.env.DATABASE_URL,
ssl: { rejectUnauthorized: false }
});


// Function to create table if it doesn't exist
const createTable = async () => {
const client = await pool.connect();
try {
const createTableQuery = `
CREATE TABLE IF NOT EXISTS your_table (
id SERIAL PRIMARY KEY,
name VARCHAR(100),
age INTEGER
);
`;
await client.query(createTableQuery);
console.log("Table 'your_table' is created or already exists.");
} catch (error) {
console.error('Error creating table:', error);
} finally {
client.release();
}
};

//Ensure table creation happen before stating the server.
(async () => {
try {
await createTable(); //attempt to create the table
} catch(error) {
console.error('Error creating table:', error);
process.exit(1); // Exit the process if the tble creation fails
}

await app.listen(port, () => {
console.log(`Server listening on port http://localhost:${port}`);
});
})();



// api Middlewares
app.use(express.json()); //and this is for accept data in json formate

app.use(express.urlencoded()); //this is i used for decode the data send through html form

app.use(cors()); // Enable CORS for all origins (not recommended for production)


//API routes

app.post('/submit-data', async (req, res) => {
console.log(req.body);

try {
const client = await pool.connect();

const { name, age } = req.body; // Extract data from request body

//validate data
if (!name || !age) {
return res.status(400).json({ msg: 'Missing required fields: name and age' })
}


const insertQuery = 'INSERT INTO your_table (name, age) VALUES ($1, $2)'; // Parameterized query
const values = [name, age];

await client.query(insertQuery, values);

res.json({ message: 'Data submitted successfully!' }); // Success response

} catch (error) {
console.error(error);
res.status(500).json({ message: 'Error submitting data' }); // Error response

} finally {
pool.release(client); // Release connection back to pool
}
});







--------------------------------------------------------------
//to avoid CORS

1. npm install cors

//write this in your top require/import section
const cors = require('cors');

// declare in middlewares
app.use(cors());  // Enable CORS for all origins (not recommended for production)


------------------------------------------------------
1. load module
const express = require('express');
const pg = require('pg');
const { Pool } = require('pg');
require('dotenv').config();
const cors = require('cors')


----------------------------------------------------
2. decribe some importatn thing

const app = express();  //this is our app or interface of express
const port = 8080; // Adjust port number as needed


---------------------------------------------------

1. Create a .env file in the root of your project and add your DATABASE_URL:

2. add you DATABASE inside .env file like  this :- DATABASE_URL=postgresql://test_owner:eSLcgdkBX9D1@ep-fragrant-boat-a56z1tgw.us-east-y.aws.neon.tech/pguser?sslmode=require

3. Load the environment variables in your application:-
// require('dotenv').config();
const express = require('express');
const pg = require('pg');

const app = express();
const port = 3000;
           
const pool = new pg.Pool({
  connectionString: process.env.DATABASE_URL,
  ssl: { rejectUnauthorized: false }
});


                    OR

//direclty use while local machine database uses

const pool = new pg.Pool({
   user: 'your_username', // Replace with your database username
   host: 'your_host', // Replace with your database host
   database: 'your_database', // Replace with your database name
   password: 'your_password', // Replace with your database password
   port: 5432 // Default PostgreSQL port
 });

// Middleware and routes...


-----------------------------------------------------------


// write query and login to create you table in database like (neon)
// Function to create table if it doesn't exist
const createTable = async () => {
  const client = await pool.connect();
  try {
    const createTableQuery = `
      CREATE TABLE IF NOT EXISTS your_table (
        id SERIAL PRIMARY KEY,
        name VARCHAR(100),
        age INTEGER
      );
    `;
    await client.query(createTableQuery);
    console.log("Table 'your_table' is created or already exists.");
  } catch (error) {
    console.error('Error creating table:', error);
  } finally {
    client.release();
  }
};

//Ensure table creation happen before stating the server.
(async () => {
try {
    await createTable(); //attempt to create the table
} catch(error) {
console.error('Error creating table:', error);
process.exit(1); // Exit the process if the tble creation fails
}

  await app.listen(port, () => {
    console.log(`Server listening on port http://localhost:${port}`);
  });
})();



-----------------------------------------------------------

1. // write API Middlewares:-
app.use(express.json()); //and this is for accept data in json formate

app.use(express.urlencoded()); //this is i used for decode the data send through html form

app.use(express.static('fronte'));// to serve our folder as  a static folder

app.use(cors());  // Enable CORS for all origins (not recommended for production)



------------------------------------------------------

1. //write API routes:-
app.get('/form', (req,res) => {
    res.sendFile(__dirname + '/fronte/index.html')
})

app.post('/submit-data', async (req, res) => {
console.log(req.body);
  const { name, age } = req.body; // Extract data from request body

  try {
    const client = await pool.connect();

    const insertQuery = 'INSERT INTO your_table (name, age) VALUES ($1, $2)'; // Parameterized query
    const values = [name, age];

    await client.query(insertQuery, values);

    res.json({ message: 'Data submitted successfully!' }); // Success response

  } catch (error) {
    console.error(error);
    res.status(500).json({ message: 'Error submitting data' }); // Error response

  } finally {
    pool.release(client); // Release connection back to pool
  }
});

--------------------------------------------
1.listen you application in your fav port
app.listen(port, () => {
console.log(`Server listening on port http://localhost:${port}`);
});



+++++++++++++++++++++++++++++++++++++++++

now you also need front-end side so write front-end code good luck

<!DOCTYPE html>
<html lang="en">

<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>

<body>
<div>
<form id="myForm">
<label for="name">change</label>
<input type="text" id="name" name="name" placeholder="Enter your name" required>
<label for="age">Age</label>
<input type="number" id="age" name="age" placeholder="Enter your age" required>
<button type="submit">Submit</button>
</form>

<script>
const form = document.getElementById('myForm');
form.addEventListener('submit', async (event) => {
event.preventDefault();
const data = {
name: document.getElementById('name').value,
age: document.getElementById('age').value
};
try {
const response = await fetch('http://localhost:8080/submit-data', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(data)
});
const result = await response.json();
console.log(result); // Handle response
} catch (error) {
console.error('Error:', error);
}
});
</script>

</body>

</html>



Comments

Popular posts from this blog

CyberSecurity

VERTICAL SCALING 💋

prisma using in project idx 13.3