Prepare code to fetch data from mock server does not seem to work

Frank Geisler 16 Reputation points MVP


I am working through this Exercise: After starting the Mock Server (I can see in the Browser that it is running) The Website has the error: Unexpected token '<', "<!doctype "... is not valid JSON

User's image

As far as I can see I have copied the source code to the right files in my project. Has someone an idea what is wrong or how I can debug this?

Thank you very much and have a nice day


ASP.NET Core Training
ASP.NET Core Training
ASP.NET Core: A set of technologies in the .NET Framework for building web applications and XML web services.Training: Instruction to develop new skills.
13 questions
{count} votes

2 answers

Sort by: Most helpful
  1. Pradeep M 1,055 Reputation points Microsoft Vendor

    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) {
      }, []);
      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();
        } catch (error) {
      const handleCreate = async (item) => {
        console.log(`add item: ${JSON.stringify(item)}`);
        try {
          const response = await fetch(API_URL, {
            method: 'POST',
            body: JSON.stringify({ name:, description: item.description }),
          const returnedItem = await response.json();
          setData([, returnedItem]);
        } catch (error) {
      const handleUpdate = async (updatedItem) => {
        console.log(`update item: ${JSON.stringify(updatedItem)}`);
        try {
          await fetch(`${API_URL}/${}`, {
            method: 'PUT',
            body: JSON.stringify(updatedItem),
          setData( => ( === ? updatedItem : item)));
        } catch (error) {
      const handleDelete = async (id) => {
        try {
          await fetch(`${API_URL}/${id}`, {
            method: 'DELETE',
          setData(data.filter(item => !== id));
        } catch (error) {
          console.error('Error deleting item:', error);
      return (
          {error && <div>Error: {error.message}</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. 

  2. AspiringDeveloper-0025 5 Reputation points

    @Frank Geisler I think there is a typo in the tutorial for vite.config.js

    Try adding host: true in the server parameters.

    So you just want an additional line slotted in...

      server: {
        port: 3000,  // Client port
        host: true,
        proxy: {
          '/pizzas': {
            target: 'http://localhost:5100', // Mock server port
    0 comments No comments