I have a basic frontend, which sends a API request to the backend and gets a json response. Very basic web application.
I want to try it on my phone and I found this link which guided me on how to do that.
How can I access my localhost from my Android device?
The problem now is, the HTML webpage/Frontend does not load the API requests, however when I go the the server from my phone I can still see the api requests going through.
Since I am doing this on my phone I cannot see the developer tools but I am 100% sure the problem isnt in my code since it works fine in getting the requests on my computer and getting the request from the server on my phone.
Anyways here is my code for the frontend
HTML
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Auction Sprint</title>
<link rel="stylesheet" href="styles.css">
<script src="index.js"></script>
</head>
<body onload="loadData()">
<header>
<div style="overflow: auto;">
<h1>Auction Sprint <img src="logo.png" alt="Logo" class="logo"></h1>
</div>
</header>
<nav>
<a href="#">Home</a>
<a href="#">Auctions</a>
<a href="#">About</a>
<a href="#">Contact</a>
<a href="#">Sign In/Login</a>
</nav>
<div class="container" id ="itemsContainer" >
<div class="auction-item">
<h2>The Death of Marat by Jacques-Louis David (Reproduction)<img src="https://cdn.britannica.com/21/7921-050-1607C28F/Death-of-Marat-Jacques-Louis-David-Royal-Museums-1793.jpg" class="preview"></h2>
<p>Category: Art</p>
<p>Seller: ArtReproductionCollector456</p>
<p>Description: Selling a reproduction of The Death of Marat by Jacques-Louis David. It's in reproduction condition. Bought it at an art fair, but need to downsize.</p>
<p>Current Bid: $500</p>
<p>Last 3 Bids: $450, $480, $490, </p>
<p>Bidding ends in: 2023-12-02T23:59:59.000Z</p>
<button class="bid-button">Bid Now</button>
</div>
<!-- Add more auction items here -->
</div>
</body>
</html>
CSS
body {
font-family: Arial, sans-serif;
margin: 0;
padding: 0;
background-color: #f0f0f0;
}
header {
background-color: #111;
color: #fff;
padding: 10px 0;
text-align: center;
}
h1 {
margin: 0;
}
nav {
background-color: #333;
padding: 10px 0;
text-align: center;
}
nav a {
color: #fff;
text-decoration: none;
padding: 10px 20px;
}
nav a:hover {
background-color: #666;
}
.container {
max-width: 1200px;
margin: 20px auto;
padding: 0 20px;
}
.auction-item {
background-color: #fff;
padding: 20px;
margin-bottom: 20px;
border-radius: 5px;
box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
text-align: left;
overflow: auto;
transition: transform 0.3s ease;
}
.auction-item:hover {
transform: translateY(-5px);
}
.auction-item h2 {
margin-top: 0;
}
.auction-item p {
margin-bottom: 0;
}
.bid-button {
background-color: #000;
color: #fff;
border: none;
padding: 10px 20px;
border-radius: 5px;
cursor: pointer;
transition: background-color 0.3s ease;
}
.bid-button:hover {
background-color: #45a049;
}
.logo {
max-width: 47px;
}
.preview {
max-width: 200px;
float: right;
}
JavaScript
async function loadData() {
try {
res = await fetch("http://localhost:4545/items")
data = await res.json()
if (!res.ok) {
console.log("problem")
return 0
}
data.forEach(element => {
itemsContainer = document.getElementById("itemsContainer")
itemDiv = document.createElement("DIV")
itemDiv.className = "auction-item"
previousBids = element.previousBids
previousBidsText = ""
for (i = 0; i < previousBids.length; i++) {
previousBidsText += `$${previousBids[i]}, `
}
itemDiv.innerHTML = `
<h2>${element.name}<img src="${element.image}" class = "preview"></h2>
<p>Category: ${element.category}</p>
<p>Seller: ${element.seller}</p>
<p>Description: ${element.description}</p>
<p>Current Bid: $${element.highestBid}</p>
<p>Last 3 Bids: ${previousBidsText}</p>
<p>Bidding ends in: ${element.endTime}</p>
<button class="bid-button">Bid Now</button>
`
itemsContainer.appendChild(itemDiv)
});
} catch (error) {
console.log(error)
}
}
and here is my code for the backend
//import Express.JS
const express = require("express");
const app = express();
//Import Mongoose for MongoDB
const mongoose = require("mongoose")
mongoose.connect("mongodb+srv://ahmad:[email protected]/ItemsDB?retryWrites=true&w=majority")
//Import itemModel.js
require("./itemModel")
//Import the model from itemModel.js
const Item_Model = mongoose.model("items_collection")
//Import Body Parser
const bodyParser = require("body-parser")
app.use(bodyParser.json())
//Import Cross Origin Resource Sharing.
const cors = require("cors");
const corsOptions ={
origin:'*',
credentials:true, //access-control-allow-credentials:true
optionSuccessStatus:200,
}
app.use(cors(corsOptions))
//create host
app.get('/',(req,res)=>{
res.send("This is our main end point")
})
//open express server
app.listen(4545, ()=>{
console.log("Connected")
})
//Create an Item
app.post("/item", async (req, res)=>{
let newItem = {
"name" : req['body']['name'],
"image" : req['body']['image'],
"description" : req['body']['description'],
"category" : req['body']['category'],
"seller" : req['body']['seller'],
"highestBid" : req['body']['highestBid'],
"previousBids" : req['body']['previousBids'],
"endTime" : req['body']['endTime']
}
let item = new Item_Model(newItem)
try{
await item.save()
console.log("new item Created")
}catch(error){
throw err
}
res.send("successfully created new item ")
})
//Read All Items
app.get("/items", async (req,res)=>{
try{
items = await Item_Model.find()
res.json(items)
}
catch(err){
console.log(err)
}
})
//Read 1 Item
/*
app.get("/item/:id",(req,res)=>{
Item_Model.findById(req.params.id).then((item)=>{
res.json(item)
}).catch(err =>{
if(err){
res.sendFile(__dirname+"/404.html")
}
})
})
*/
app.get("/item/:id", async (req, res) => { //< Marks the callback as async
try{
const item = await Item_Model.findById(req.params.id); //< Use of await keyword
if(!item){ //< item will be null if no matches in database
return res.status(400).sendFile(__dirname+"/404.html") //invalid id //return res.status(400).json({message: 'No Item found'})
}
return res.status(200).json({
item: item
});
} catch(err){
//console.log(err); //< Log the actual error so you can check
return res.status(500).sendFile(__dirname+"/404.html"); //invalid id less than 26 char
// i want to send a message to html error page and redirect them to it
}
});
//Delete an Item
app.delete("/item/:id", async (req,res)=>{
try{
item = await Item_Model.findOneAndDelete({"_id":req.params.id})
console.log(item)
res.send("Item Successfully Removed")
}catch(err){
console.log(err);
}
})
//Redirect If page Doesn't exist
app.get("*",(req,res)=>{
res.sendFile(__dirname+"/404.html")
})