When using AngularJS and Laravel together, the CORS functionality may cause the POST request to halt after the preflight

Once upon a time, there was a bird who dreamt of joining the postal service but failed his preflight test...

Using Laravel as a RESTful API and AngularJS/ionic for the app, everything was working smoothly until suddenly... it stopped. The withCredentials setting on the Angular side seemed to be causing issues with the preflight OPTIONS not sending a cookie, even though Laravel was returning one. How can we prevent OPTIONS from returning a laravel_session cookie? This is causing CORS problems by creating a new session with every POST request. I've implemented Laravel/CORS package by @barryvdh with the configuration:

 '*' => array(
'supportsCredentials' => true,
'allowedOrigins' => array('*'),
'allowedHeaders' => array('*'),
'allowedMethods' => array('POST', 'PUT', 'GET', 'PATCH', 'OPTIONS', 'DELETE'),
'maxAge' => 36000,
'hosts' => array('api.*'),
)

On the Angular side, I have:

$http({
method: 'POST',
url: 'http://api.blabla.local/banana',
data: data,
withCredentials: true
})

All GET calls are working fine, including fetching the CSRF token from Laravel at the start of the app.

The current situation is as follows:
1. Preflight OPTIONS > no session cookies in the request. Response = 200 with a different session cookie causing CSRF errors. [my belief: withCredentials doesn't work with OPTIONS call]
2. POST > fails with 500 error, headers show no response even though the cookie/session was sent. Error message indicates unauthorized origin.

What could be causing this issue? I've spent hours troubleshooting and reading other posts without success. Can we eliminate the preflight somehow or is the problem elsewhere (perhaps with Laravel Homestead)? It seems like the main problem lies in the OPTIONS request returning a session cookie or the request itself including one!

Any help would be greatly appreciated, I'm going crazy trying to solve this...

Answer №1

After some trial and error in filters.php around line 4.2, I came up with this solution: It's tough to pinpoint the exact fix due to the age of the issue, but it seems like this did the trick:

App::before(function($request)
{
    //
    // Enabling CORS 
    // For production, replace * with http://yourdomain.com 
    header("Access-Control-Allow-Origin: http://mydomain.local");
    header('Access-Control-Allow-Credentials: true'); //optional
    if (Request::getMethod() == "OPTIONS") {
        // The client-side application can only set headers allowed in Access-Control-Allow-Headers
        $headers = [
            'Access-Control-Allow-Methods'=> 'GET, POST, PUT, DELETE',
            'Access-Control-Allow-Headers'=> 'Content-Type'
        ];
        return Response::make('You are connected to the API', 200, $headers);
    }

});


App::after(function($request, $response)
{
    //
});

Answer №2

Utilizing JWT can greatly benefit both Ionic and Angular development.

To learn more about JWT check out this link and also watch a tutorial on the topic at this YouTube video

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

Changing the structure of a webpage in real-time and inserting new elements into the document

I have a custom x-template filled with a survey element (including a text field and radio button). Upon loading the screen, the database sends a JSON object to the UI based on previously stored sections. This JSON object is then used to populate the survey ...

How do I ensure that AngularJS module routes make use of their own controllers?

I am currently delving into the intricacies of AngularJS' view and routing system by following AngularJS' official tutorial. One issue I have encountered is that the tutorial declares all controllers in the global scope, which I consider to be a ...

How can I bring in a dynamic MaterialUI theme object from another file?

Could anyone provide guidance on the correct syntax for importing a dynamic theme object from a separate file? I am attempting to retrieve the system theme based on a media query and then dynamically set the theme. Everything works as expected when all t ...

Can you provide some insight on how to store XMLHttpRequest response in Javascript for future

I have a function in my codebase that is responsible for loading HTML templates asynchronously: loadTemplate: function(url) { return new Promise(function(resolve, reject) { var xhr = new XMLHttpRequest(); xhr.open("GET" ...

Using Pocketbase OAuth in SvelteKit is not currently supported

I've experimented with various strategies, but I still couldn't make it work. Here's the recommendation from Pocketbase (): loginWithGoogle: async ({ locals }: { locals: App.Locals }) => { await locals.pb.collection('users' ...

What is the best way to produce a random integer within the range of 0 and 2

Here is the code snippet: var i = prompt('Please choose Rock, Paper or Scissors:'); var b = ['Rock', 'Paper', 'Scissors']; Now, I need help in generating a random number between 0-2. My initial idea was to do t ...

Managing the file order within subdirectories for Rails assets

Utilizing rails to power a primarily single page application, I am incorporating angular as well. Within my assets/javascripts directory, I have organized folders for controllers, directives, filters, routes, services, and more. Certain elements, such as ...

The functionality of core-ui-select is not functioning properly following the adjustment of the

I've implemented the jquery plugin "core-ui-select" to enhance the appearance of my form select element. Initially, it was functioning perfectly with this URL: However, after applying htaccess to rewrite the URL, the styling no longer works: I&apos ...

Angular: Design dependent on attributes

Can I customize the styling of a div in accordance with a boolean property called "isActive" on my controller using Angular? <div class="col-md-3" (click)="isActive = !isActive"> <div class="center"> <i class="fa fa-calendar"& ...

Tips on revealing concealed information when creating a printable format of an HTML document

I need to find a way to transform an HTML table into a PDF using JavaScript or jQuery. The challenge I'm facing is that the table contains hidden rows in the HTML, and I want these hidden rows to also appear in the generated PDF. Currently, when I co ...

Is there a way to access a comprehensive list of all the set-up WebApi routes within asp.net MVC?

I am currently working on passing configuration values to initialize a single page AngularJs application embedded within an MVC application that makes use of WebApi (as shown below in the Razor view, achieved by inheriting a BasePage and injecting a Serial ...

Using BrowserSync with Angular can cause issues with form submission mechanisms

Situation: I currently have a form set up like this: <div ng-controller="ChatController"> <form ng-submit="sendTextMessage()"> <input type="text" class="form-control" ng-model="msgInput"> </form> </div> Addit ...

Stop the npm start command with a specific error message if the file is not found in the repository

Can the npm start process be stopped or cancelled if a specific file is not found in your codebase? I am looking to end the process if the file dev-variables.js is missing, preferably displaying a custom error message like "You are missing the dev-variabl ...

How can I retrieve an attribute from another model in Ember using the current handlebar in the HTML file?

I'm attempting to achieve the following: {{#if model.user.isAdmin}} <div> My name is {{model.user.name}} </div> {{/if}} within a handlebar that is being used in a controller unrelated to users: <script type="text/x-handlebars" data- ...

In the strict mode tree, a reference named "grid" has been discovered

I encountered the following warning in the console: Warning: A string ref, "grid", has been found within a strict mode tree. String refs can potentially lead to bugs and should be avoided. It is recommended to use useRef() or createRef() instead. T ...

Tips for sending information to an Express API through AJAX

While working on a website using Express and EJS, I encountered an issue with calling an API via AJAX. The problem arises when passing two values to the AJAX data upon button click, resulting in errors. Despite trying various solutions, I'm still stru ...

Calling a C# Webmethod using jQuery AJAX is not working as expected

I'm currently facing an issue calling a web method that I created. The problem lies in the fact that the ajax call isn't reaching my web method, which is puzzling to me because I have another web method in the same file with the same return type ...

What is the optimal method for transmitting both an image and JSON data to my express server?

Hey there! So I've set up a MongoDB database and I'm using Mongoose to work with it. Here's the model I have for my product: const productSchema = new Schema({ name: { type: String, required: true}, description: { type: String, required ...

Styling the "Browse" button for different web browsers

Here is the code snippet I am working with: HTML: <form> <input id = "file" type="file" /> <div id="custom_button">custom button</div> </form> Jquery: $("#custom_button").on("click", function () { $("#file"). ...

What makes components declared with "customElements.define()" limited in their global usability?

I've been tackling a project in Svelte, but it involves some web components. The current hurdle I'm facing is with web components defined using the customElements.define() function in Typescript, as they are not accessible unless specifically im ...