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

I am unable to determine if I have already selected a List Item

My goal is to have a functionality where clicking on "Download Drivers" will open the list, and clicking again will close it. This should be achieved with onclick events only, no hover effects. Additionally, I want the list to remain open even if I click o ...

Data from AngularFire not displaying in my list application

While going through tutorials on the Angular website, I encountered a roadblock while attempting to create a list that utilizes Firebase for data storage. Strangely, everything seems to be functional on the Angular site, but clicking on the "Edit Me" link ...

"How can we pause the setInterval when the user hovers over the Ajax Quick Cart and resume it once

Currently, I am working on configuring my Ajax Quick Cart to delay a setInterval function when the user hovers over the cart. The goal is to have the cart close automatically after 3 seconds once an item has been added. However, as I'm not very profic ...

Having trouble obtaining outcomes from Cloud Code in Parse

After struggling with this issue for quite some time, I have reached a point where I feel the need to seek help. I am working on a cloud code function that is supposed to retrieve a list of categories along with their respective products. Each category con ...

Dynamically remove values from other fields in a React Formik form based on checkbox conditions

Currently, I am utilizing react-formik for my form implementation. I have encountered an issue with checkbox-based conditions where the checked status of a checkbox determines whether two hidden fields are displayed or hidden. If the user checks the checkb ...

Similar to Angular ui-router 1.0.3, what is the equivalent function for reloadOn

After updating to UI-router v1.0.3 from v0.3.2, I noticed that the reloadOnSearch feature has been removed from the stateConfig. I'm having trouble finding the equivalent of reloadOnSearch in v1.0.3. It doesn't seem to be documented anywhere. A ...

Using NSLog to fetch an NSCFString from the objectAtIndexedSubscript method within the cellForRowAtIndexPath function

After completing my app using a certain method, I am now trying to implement a simple JSON response that needs to be parsed. However, I keep encountering the following error: [__NSCFString objectAtIndexedSubscript:]: unrecognized selector sent to instan ...

Execute a simulated click function in JavaScript without causing the viewport to move

I have successfully implemented a sticky add to cart feature on my Shopify store. However, there seems to be an issue where clicking on the variations in the sticky area also triggers the same variations on the product page, making it difficult for users t ...

Is your Laravel and vue js "add to cart" button malfunctioning?

Hey there! I'm currently working on an e-commerce project using Laravel and Vue. I have successfully managed to add products to the cart, but I'm facing an issue where the quantity in the cart remains at 0 until I refresh the page. I've trie ...

Troubleshooting a 404 error for an existing object: What to do?

I encounter a 404 'Not Found' error when attempting to edit a mark through my form. I am puzzled by the source of this error because in order to access this form, I require the brand ID (which can be found in the URL). Upon accessing my modifica ...

Struggling to display sub-categories correctly within the Categories Dropdown menu

Attempting to display sub-categories in the Categories Dropdown list In my code, I aim to display category and sub-category under the Category in the Products table. This is how my categories table looks: 1. public function up() { Schema::create(&apos ...

Adaptable Semantic UI form design

Welcome, internet friends! If anyone out there has a moment to spare and is familiar with Semantic UI, I could really use some assistance... Currently, I am working on a form that looks great on larger screens like this: https://i.stack.imgur.com/cafc5.j ...

Colorbox: Display a specific section from a separate HTML page

Currently, I am facing a challenge where I need to open just one specific part of an external HTML page in a colorbox. I attempted the following approach, however it is opening the entire page instead of just the specified part (at the div with id="conten ...

Using AngularJS to auto-populate additional fields after selecting an option from the typeahead autocomplete feature

Just starting with AngularJS and finally figured out how to implement Auto-complete in Angularjs. Now, when a user selects a value from the auto-complete, I want other fields to be populated based on that selection. For example, upon loading the screen, d ...

Unlimited scrolling gallery with multiple rows

I am looking for a way to create a multi-row infinite loop scrolling gallery using html, css, and javascript. Can anyone help me with this? ...

What is the best way to send a variable using $.post in a JavaScript script?

My jQuery and Javascript code below is responsible for handling the ajax request: else { $.post("http://www.example.com", {email: val}, function(response){ finishAjax('email', response); }); } joi ...

The console is showing an error message stating that the variable "i" is not

Currently, I am developing the dashboard for my discord.js bot. While working on it, I encountered an issue where a variable I created to select an array from my JSON file is being reported as undefined by the console. $(function() { $.getJSON( "./data/ ...

Supply mandatory argument along with varying arguments to the function

I have a function that requires one parameter and a dynamic set of additional parameters. I am passing an array of blobs to the function. Below is a simplified version of the function: function test(directory, blob0, blob1) { for (var argumentIndex = 1; ...

Exploring the power of AngularJS with ng-click functionality and utilizing services

As a beginner in AngularJS, I am facing a knowledge gap when it comes to integrating a barcode scan feature into my application. What I want to achieve is quite simple - a button in the view that, when clicked, triggers a barcode scan. Once the scan is com ...

JavaScript overlay that does not interact with HTML elements directly

Currently, I am facing the challenge of implementing a javascript overlay upon page load without direct access to the html code. My only options are to upload .js and .css files. I have extensively searched for solutions, but as someone with limited exper ...