Laravel does not have the capability to provide a genuine json response

I am facing an issue with my Laravel controller. The code is straightforward:

class MyController extends Controller
{
    public function list()
    {
        return response()->json(['a' => 'hello']);
    }
}

When I access the corresponding URL in Google Chrome, everything works as expected. I receive a response {"a":"hello"} with the content type of application/json.

However, when trying to fetch the data using JavaScript (utilizing the fetch polyfill), I notice that the content type shows up as text/html. This discrepancy was verified both in Google Chrome DevTools and within my code:

fetch("/list")
    .then(function(response) {
        console.log(response.headers.get('Content-Type')); // => 'text/html'
        return response.json();
    })
    .then(function(json) { 

    })
    .catch(function(error){

    });

Unfortunately, this situation leads to an error -

Unexpected token < in JSON at position 0
.

I am puzzled by what could be causing this.

PS:

Laravel version - 5.4, PHP Version 7.0.15, XAMPP 3.2.2

Fetch polyfill version - 2.0.3

Google Chrome version - 57.0.2987.133

Oddly enough, this problem seems to work correctly in Microsoft Edge v.20.10240.

Answer №1

To ensure your request is sent in JSON format, make sure to specify the content type as json in the header. If you are using jQuery, you can do it like this:

 $.ajax({
                type: 'GET',
                url: url,
                contentType: 'application/json; charset=utf-8',
                success: 
                error: 
            });

Answer №2

I recently encountered an issue with authentication while setting up my routes. I realized the problem was with using the session auth for all routes, but utilizing api routes like this helped me:

Route::middleware('auth:api')->get('/list', 'ApiController@list');

Additionally, I made sure to include the api_token in all of my requests as explained in this reference guide here.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Add the scss file to the vuejs component npm package only if certain conditions specified in the project are met

Creating css/scss themes for my Vue Components Npm package has been a focus of mine lately. This particular package is local and currently being tested using npm link. Both the Package and Project are utilizing webpack. index.js of Package import "./src ...

Initial page load experiencing issues with paroller.js functionality

Upon hard refreshing the page in the middle section, there seems to be an issue with the paroller js transform: translateY(); CSS effect not functioning properly on the <div class="col col-6" data-paroller-factor="0.4" data-paroller-type="foreground" da ...

Minimize CPU consumption in your threejs application

I've been working on a project where I'm coding Snake in Threejs (I know there are simpler methods). Everything works smoothly until the snake reaches a certain size, causing CPU usage to spike to 50% or more and freezing the entire browser tab. ...

The variable is unable to be accessed within the PHP function query

After passing a variable through ajax to a function within my php file "Cart_code.php", I encountered an issue where the variable was not accessible inside the function. Can you help me figure out why? Javascript $.ajax({ type: "POST", url: "incl ...

Tips for dynamically sending data without explicitly stating the name:

Looking to create a JSON structure with name and value pairs such as name:"john". Check out the code snippet below: var allFields = []; var inputs = document.getElementsByTagName('input'); for(var i=0; i<inputs.length;i++){ name = in ...

Implementing dynamic component swapping in Vue 3 using components from another component

I currently have a display component called app-display, which contains a dynamic component inside (by default, it is set to app-empty): app.component('appDisplay', { template: `<component :is="currentComponent"></c ...

Can one determine if a webpage is being displayed within an Infragistics igDialog?

Occasionally, my web page is displayed without a container and other times it's embedded within an igDialog of another container page, based on the user's navigation throughout our web application. Is there a way, using pure javascript or jQuery ...

When trying to access data within objects using JSON iteration, it may lead to encountering an issue of reading a

Attempting to retrieve specific data from a JSON file obtained from a website has proven challenging. While iterating through the collection of objects, undefined values are constantly encountered. Unfortunately, if the JSON is poorly structured, modificat ...

What is the best way to incorporate a <c:forEach> loop into JSP operations?

I am attempting to calculate the product of two variables that are associated with an item in a loop. Below is the code snippet from the JSP file: <table> <thead> <tr> <th>PRICE</th> <th ...

Adding the unzip feature is not within my capabilities

I am a novice Japanese web developer. Unfortunately, my English skills are not great. I apologize for any inconvenience. I am interested in utilizing this specific module: https://www.npmjs.com/package/unzip To do so, I executed the following commands ...

Screen the received JSON data for a specific section of the website

Is there a way to extract Json data from a website using "selenium.captureNetworkTraffic("json")"? I need to refine the results for a specific grid on my website which contains multiple grids. How can I filter the data for a particular grid? Additionally ...

Error in electron-builder: Module 'dmg-license' was not found

Seeking a straightforward method to create an electron app for macOS from a Linux machine. Unfortunately, the electron-builder -m command is not functioning properly. Here is the complete output of the command: electron-builder -m • elec ...

When utilizing webpack in Angular 5, the :host selector does not get converted into a component entity

Initially, I set up Angular with webpack following the configuration in this guide, including configuring webpack sass-loader. Everything was working smoothly until I encountered an issue today: app.component.ts @Component({ selector: 'ng-app&ap ...

Having trouble with an onClick function not working on a .php webpage?

I recently developed a simple JavaScript script that dynamically loads an image based on user input in a text field (e.g., entering 'brick1' loads brick1.jpg). Although this works fine on a regular HTML page, I faced issues triggering the onClick ...

Tips for concealing a collapsible navbar menu upon clicking elsewhere (Bootstrap 5)

I am trying to create a collapsible navbar menu: <div class="collapse navbar-collapse" id="navbarCollapsible"> .. menu items .. </div> My goal is to hide the menu whenever a user clicks outside of it (not just when click ...

Issue with Material UI Tab component not appearing in the first position

I've encountered an unusual problem where the first tab is not displaying correctly. To troubleshoot, I added a second tab which appeared perfectly fine. After setting up the second tab to have the desired content of the first tab, I deleted the origi ...

The system couldn't locate the module: Issue: Unable to find module 'fs' within the directory

I am currently working on integrating the ADAL JS sample code from this link into a SharePoint framework client web part. My code is fairly straightforward, as I have already installed packages like adal, fs, and node-fs using NPM. However, when running t ...

Overlapping problem with setInterval

I am currently working on a project that requires the use of both setInterval and setTimeout. I am using setTimeout with dynamic delays passed to it. While elements are not timed out, I have implemented setInterval to print out numbers. Here is the code ...

Load a JSON file into the app.js of your project

Could someone please help me figure out how to successfully load a JSON file into my project's app.js? I've tried using the following code snippet: var j = require('./JSON1'); However, it didn't work as expected. My goal is to la ...

What is the best way to make sure the background color of a container stretches across the full width of the screen?

I am currently learning HTML and CSS, and as a practice project, I am working on building a portfolio webpage. In the image provided, there are two containers, and I am facing an issue with the space on the sides when changing the background color. Despite ...