After deploying react app into azure web app service, I had an issue as the login page renders normally, once I refresh it, I got this error displayed:
The resource you are looking for has been removed, had its name changed, or is temporarily unavailable.
After spending some time, the solution I found was to add a web config file, which is this one:
<configuration>
<system.webServer>
<rewrite>
<rules>
<rule name="AngularJS Routes" stopProcessing="true">
<match url=".*" />
<conditions logicalGrouping="MatchAll">
<add input="{REQUEST_FILENAME}" matchType="IsFile" negate="true" />
<add input="{REQUEST_FILENAME}" matchType="IsDirectory" negate="true" />
</conditions>
<action type="Rewrite" url="/" />
</rule>
</rules>
</rewrite>
<caching enabled="true" enableKernelCache="true">
<profiles>
<add extension=".js" policy="DisableCache" kernelCachePolicy="DisableCache" />
</profiles>
</caching>
</system.webServer>
</configuration>
Now, most of the things work well, however, the product page has some issues. You can see it on the gif, but once I click on a product, the product page renders well and as soon as I try to refresh it, the page becomes blank. Also, the logo is not showing only there and the header's nav menu is not clickable.
And this is the error in the console:
index.js
import React, {useState, useEffect} from 'react';
import { BrowserRouter, Routes, Route, Navigate } from 'react-router-dom';
import ReactDOM from 'react-dom/client';
import Header from './header.js';
import Product from './product.js';
import MainPage from './main.js';
import Cart from './cart.js';
import Login from './login.js';
import Admin from './adminDashboard.js';
import { getUserDataFromToken } from './authService';
// This function checks if the user is authenticated
function isAuthenticated() {
const token = localStorage.getItem('userToken');
if (token) {
const payload = JSON.parse(atob(token.split('.')[1]));
// Check if token has expired
return payload.exp > Date.now() / 1000;
}
return false;
}
// This component wraps around the protected route's element
function PrivateRoute({ children }) {
return isAuthenticated() ? children : <Navigate to="/login" />;
}
function App() {
const [user, setUser] = useState(null);
useEffect(() => {
const userData = getUserDataFromToken();
if (userData) {
setUser(userData.email);
}
}, []);
//console.log(user);
return (
<BrowserRouter>
<div>
<Routes>
<Route index element={<PrivateRoute><MainPage/></PrivateRoute>} />
<Route path="/product/:productId" element={<PrivateRoute><Product product={6}/></PrivateRoute>} />
<Route path="" element={<PrivateRoute><Cart /></PrivateRoute>} />
<Route path="/admin" element={<Admin />} />
<Route path="/login" element={<Login />} />
</Routes>
</div>
</BrowserRouter>
);
}
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(<App />);
product.jsx
function App() {
let productID = window.location.pathname.split('/')[window.location.pathname.split('/').length-1];
var [CurrentProduct, setProduct] = useState([]);
var [loading, setLoading] = useState(true);
useEffect(() => {
const url = "https://myapi.net/Product/FindProduct/" + productID;
fetch(url)
.then((response) => response.json())
.then((data) => setProduct(data));
console.log("GETTING DATA FROM SERVER");
setLoading(false);
}, [loading]);
console.log(CurrentProduct);
if (loading)
{
return <p>Loading...</p>;
}
if (!loading && CurrentProduct.id > 0)
{
return (
<div className={styles.productPage}>
<Header />
<div className={styles.fullPage}>
<ProductImages product={CurrentProduct} />
<ProductDetails product={CurrentProduct} />
<Comments product={CurrentProduct} />
<AddReview product={CurrentProduct} setLoading={setLoading} />
</div>
</div>
);
}
}
export default App;
Any advices on how to fix the issue would be appreciated!
"Uncaught SyntaxError: Unexpected token '<'"
This usually happens when the server returns an HTML response instead of JavaScript code. it seems like the server might be returning an HTML error page instead of the expected JSON response from the API call in your product.jsx
file.
Product.js:
import React, { useState, useEffect } from 'react';
function Product() {
const [product, setProduct] = useState({});
const [loading, setLoading] = useState(true);
useEffect(() => {
// Fetch product data from API endpoint
fetchProductData();
}, []);
const fetchProductData = async () => {
try {
const response = await fetch('https://app-name.azurewebsites.net/Product/FindProduct/382183');
const data = await response.json();
setProduct(data);
setLoading(false);
} catch (error) {
console.error('Error fetching product data:', error);
setLoading(false);
}
};
if (loading) {
return <p>Loading...</p>;
}
return (
<div>
<h2>{product.name}</h2>
<p>{product.description}</p>
<p>Price: ${product.price}</p>
<p>Category: {product.category}</p>
<img src={product.image} alt={product.name} style={{ maxWidth: '300px' }} />
</div>
);
}
export default Product;
Additionally, if you have any CORS (Cross-Origin Resource Sharing) restrictions set up on your backend API.
Product
component within the routes using react-router-dom
.import React from 'react';
import { BrowserRouter as Router, Routes, Route } from 'react-router-dom';
import Product from './Product';
function App() {
return (
<Router>
<div>
<Routes>
<Route path="/product" element={<Product />} />
</Routes>
</div>
</Router>
);
}
export default App;
Above API endpoint returns the expected JSON response containing product details.