Hi Frank Geisler,
Thank you for reaching out to Microsoft Q & A forum.
Steps to Resolve the Issue:
1.Ensure Mock Server is Running Correctly
First, make sure your mock server is up and running. You should be able to access “http://localhost:5100/pizzas” in your browser and see the mock data:
[
{ "id": 1, "name": "Margherita", "description": "Tomato sauce, mozzarella, and basil" },
{ "id": 2, "name": "Pepperoni", "description": "Tomato sauce, mozzarella, and pepperoni" },
{ "id": 3, "name": "Hawaiian", "description": "Tomato sauce, mozzarella, ham, and pineapple" }
]
2.Verify Vite Proxy Configuration
Open your “vite.config.js” file and ensure it looks like this:
import { defineConfig } from 'vite';
import react from '@vitejs/plugin-react';
export default defineConfig({
plugins: [react()],
server: {
port: 3000, // Client port
proxy: {
'/pizzas': {
target: 'http://localhost:5100', // Mock server port
changeOrigin: true,
secure: false,
ws: true,
configure: (proxy, _options) => {
proxy.on('error', (err, _req, _res) => {
console.log('proxy error', err);
});
proxy.on('proxyReq', (proxyReq, req, _res) => {
console.log('Sending Request to the Target:', req.method, req.url);
});
proxy.on('proxyRes', (proxyRes, req, _res) => {
console.log('Received Response from the Target:', proxyRes.statusCode, req.url);
});
},
}
}
}
});
3.Update Your React Component to Handle Errors
Modify your “Pizza.jsx” file to handle errors gracefully and use “async/await” for fetch operations:
import { useState, useEffect } from 'react';
import PizzaList from './PizzaList';
const term = "Pizza";
const API_URL = '/pizzas';
const headers = {
'Content-Type': 'application/json',
};
function Pizza() {
const [data, setData] = useState([]);
const [error, setError] = useState(null);
useEffect(() => {
const fetchData = async () => {
try {
await fetchPizzaData();
} catch (error) {
setError(error);
}
};
fetchData();
}, []);
const fetchPizzaData = async () => {
try {
const response = await fetch(API_URL);
if (!response.ok) {
throw new Error('Network response was not ok');
}
const jsonData = await response.json();
setData(jsonData);
} catch (error) {
setError(error);
}
};
const handleCreate = async (item) => {
console.log(`add item: ${JSON.stringify(item)}`);
try {
const response = await fetch(API_URL, {
method: 'POST',
headers,
body: JSON.stringify({ name: item.name, description: item.description }),
});
const returnedItem = await response.json();
setData([...data, returnedItem]);
} catch (error) {
setError(error);
}
};
const handleUpdate = async (updatedItem) => {
console.log(`update item: ${JSON.stringify(updatedItem)}`);
try {
await fetch(`${API_URL}/${updatedItem.id}`, {
method: 'PUT',
headers,
body: JSON.stringify(updatedItem),
});
setData(data.map(item => (item.id === updatedItem.id ? updatedItem : item)));
} catch (error) {
setError(error);
}
};
const handleDelete = async (id) => {
try {
await fetch(`${API_URL}/${id}`, {
method: 'DELETE',
headers,
});
setData(data.filter(item => item.id !== id));
} catch (error) {
console.error('Error deleting item:', error);
}
};
return (
<div>
<PizzaList
name={term}
data={data}
error={error}
onCreate={handleCreate}
onUpdate={handleUpdate}
onDelete={handleDelete}
/>
{error && <div>Error: {error.message}</div>}
</div>
);
}
export default Pizza;
4.Reset and Rebuild Your Dev Container
Since you mentioned issues with your development environment, let's reset and rebuild it:
Stop and remove all running containers: “docker-compose down”
Prune unused Docker resources: “docker system prune -f”
Open your project in VS Code, use the Command Palette (F1), and select "Remote-Containers: Rebuild and Reopen in Container".
5.Restart Services
Ensure all dependencies are installed before starting the servers:
In one terminal, start the mock server:
npx json-server --watch --port 5100 db.json
In another terminal, start the Vite development server:
npm install
npm run dev
6.Inspect Network Requests
Use the browser’s developer tools to inspect network requests:
Open your app in the browser and go to the Network tab.
Look for requests to “/pizzas” and ensure they are being proxied to “http://localhost:5100/pizzas” and returning JSON data.
Please feel free to contact us if you have any additional questions.
If you have found the answer provided to be helpful, please click on the "Accept answer/Upvote" button so that it is useful for other members in the Microsoft Q&A community.
Thank you.