Microsoft Azure static React App not returning json

182 views Asked by At

I'm hoping someone else has encountered and solved this issue. We have a React app deployed to Azure Static Web App. The app works fine, but we can't figure out how to configure it to return JSON instead of HTML in its responses.

We have a file as part of the app called:

staticwebapp.config.json

{
  "navigationFallback": {
    "rewrite": "/index.html",
    "exclude": ["/static/media/*.{png,jpg,jpeg,gif,bmp}", "/static/css/*"]
  },
  "mimeTypes": {
    ".json": "text/json"
  }
}

Can someone help us figure out how to solve this issue? We can provide more information if needed.

Our React app deployed to Azure Static Web App is returning HTML instead of JSON in its responses. (It is returning index.html ???) I've tried many things, including setting the homepage in package.json to "." and removing it altogether, but nothing has worked. I've also read the entire Microsoft documentation on configuring static apps, could not find any helpful information.

enter image description here

enter image description here

1

There are 1 answers

1
Suresh Chikkam On

There's a small issue with the "mimeTypes" section. The MIME type should be set to "application/json" to ensure that JSON files are correctly recognized and served as JSON responses.

{
  "mimeTypes": {
    ".json": "application/json"
  }
}
  • There is a technical reason for specifying the correct MIME type when serving JSON files. MIME (Multipurpose Internet Mail Extensions) types are used to indicate the type and format of files served over the internet. The MIME type informs the browser and client how to handle the content it receives. In the case of JSON, specifying the correct MIME type is essential for several reasons.

Second approach:

You can create an Azure Function that returns JSON and then call that function from your React app.

  • Create a sample Azure Function:
module.exports = async function (context, req) {
    context.res = {
        headers: {
            'Content-Type': 'application/json'
        },
        body: {
            message: 'Hello, world!'
        }
    };
};
  • Then call this function from your React app using the fetch API:
fetch('/api/hello')
    .then(response => response.json())
    .then(data => console.log(data));

  • The below message will log on the console:
{ message: 'Hello, world!' }