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

Frank Geisler 21 Reputation points MVP
2024-05-28T19:02:39.45+00:00

Hi!

I am working through this Exercise: https://learn.microsoft.com/en-us/training/modules/build-web-api-minimal-spa/5-exercise-create-api. 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

Frank

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.
27 questions
{count} votes

2 answers

Sort by: Most helpful
  1. Pradeep M 4,095 Reputation points Microsoft Vendor
    2024-05-31T06:05:57.1066667+00:00

    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. 


  2. AspiringDeveloper-0025 15 Reputation points
    2024-06-05T03:55:37.7033333+00:00

    @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

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.