Thanks to visit codestin.com
Credit goes to www.scribd.com

0% found this document useful (0 votes)
8 views5 pages

Program 7

Uploaded by

Jyothi Jyothi
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views5 pages

Program 7

Uploaded by

Jyothi Jyothi
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 5

import express, { json } from 'express';

const app = express();


app.use(json());

app.get('/', (req, res) => {


res.send('Hello! ');
});
const products=[
{ id:1,
name:"mi"
},
{ id:2,
name:"iphone"
},
{ id:3,
name:"oppo"
}
]
app.get('/products', (req, res) => {
res.send(products);
});

app.get('/products/:id', (req, res) => {


const
newData=products.filter(item=>item.id.toString()===req.params.id)
res.send(newData);
});

app.post('/addproducts', (req, res) => {


var id=products.length+1;
const {name } = req.body;
const newProduct = {id,name };
products.push(newProduct);
res.send(products);
});

app.put('/updateproducts/:id', (req, res) => {


const product = products.find(item => item.id.toString() ===
req.params.id);
product.id = req.body.id;
product.name = req.body.name;
res.json(products);
});

app.delete('/deleteproducts/:id', (req, res) => {


const index = products.findIndex(item => item.id.toString() ===
req.params.id);
const deletedProduct = products.splice(index, 1);
res.send(deletedProduct);
});

app.listen(3000, () => {
console.log('Server running on http://localhost:3000');
});

Program 8
Steps :
1. Download and install MongoDB and create database named
‘shop’ and create collection ‘products’ in the shop DB.
2. Create Folder Labprogram8 .
3. Create sub folders frontend and backend in Labprogram 8.
4. Frontend must have react app with App.js.
5. Backend is a express project with server.js
Sever.js
import express, { json } from 'express';
import cors from 'cors';
import mongoose from "mongoose";
const router = express();
router.use(json());
router.use(cors());

// MongoDB connection

const DB_URL = 'mongodb://localhost:27017/shop';


mongoose.connect(DB_URL);

// Define Schema and Model


const productschema = new mongoose.Schema({ name: String, cost : Number ,pid:
Number});
const Product = mongoose.model('Product', productschema);

// Define End Points

router.get('/products', async (req, res) => {


res.set('Access-Control-Allow-Origin', '*')
try {
const products = await Product.find();
res.json({data:products});

} catch (error) {
res.status(500).json({message:'error fetching products',error})
}
});

router.listen(3000, () => { console.log('Server running on http://localhost:3000') } );

App.jsx
import { useEffect, useState } from 'react'
import './App.css'

function App() {
const [products, setProducts] = useState([]);
const [responseMessage, setResponseMessage] = useState('');
useEffect(() => { fetchData() }, [])

async function fetchData() {


try{
console.log('am in fetch data')
const response = await fetch("http://localhost:3000/products")
if(!response.ok)
console.log ("no respose" + response.status);

const res = await response.json();


//const data = res.data;
setProducts(res.data);

} catch (error){ console.log(error)}


}

return (
<div>
<h2>Product List</h2>
<h3> Web Application developed using MERN</h3>
<ul> {products.map((p,i) => (<li key = {p._id}> {p.pid }- {p.name} - RS{p.cost} </li>) )}
</ul>

<form id="adddata" onSubmit={handleSubmit}>


<input type="text" name="pdid" placeholder="PID" />
<input type="text" name="pname" placeholder="Name" />
<input type="text" name="pcost" placeholder="Cost" />
<button type="submit">Add</button>
</form>
</div>
);
}
export default App;

You might also like