M
M
Maxim Kutenkov2020-10-19 16:08:34
PHP
Maxim Kutenkov, 2020-10-19 16:08:34

Why is a post request (cross domain) not sent from vuejs(axios) to laravel?

Vuejs is installed on the site with the form, axios are on the domain: https://domain1.ru , Laravel is deployed on IIS with the domain: https://domain2.ru , api access is via Passport, all controllers are created, via POSTMAN requests exit without any errors.

But as soon as I send the form from https://domain1.ru to https://domain2.ru/api/createOrder, then the error "Access to XMLHttpRequest at 'https://domain2.ru/api/createOrder' falls on the site with the form from origin ' https://domain1.ru ' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource."

I rummaged all over Google and Yandex did not find anything that could solve my problem. I hope for your help.
The server returns the required headers. Installed the CORS intermediary on Laravel.
In the browser in the console-network, when submitting the form, there are two lines to this API, one with a CORS error, the second with headers and the OPTIONS request method and a 200 response.

The submitForm code:

formSubmit(e) {
            var payload = {
                id_service: this.servicesModel,
                object_type: this.typeObjModel,
                object_address: this.address,
                object_area: this.areaStr,
                branch_id: this.branchModel,
                order_name: this.orderName,
                order_phone: this.orderPhone,
                order_email: this.orderMail,
                comments: this.comments
            };
            e.preventDefault();
            let currentObj = this;
            axios.post('https://домен2.ру/api/createOrder',
            payload,{
                method: 'POST',
                mode: 'no-cors',
                headers: {
                    'Accept': 'application/json',
                    'WithCredentials': true,
                    'Access-Control-Allow-Origin': '*',
                    'Content-Type': 'application/json',
                    'Authorization': ''
                },
                withCredentials: true,
                credentials: 'same-origin',
            })
            .then(function (response) {
                currentObj.output = response.data;
            })
            .catch(function (error) {
                currentObj.output = error;
            });
        }

POST response with CORS error
Request URL: https://домен2.ру/api/createOrder/
Referrer Policy: no-referrer-when-downgrade
Provisional headers are shown
Accept: application/json, text/plain, */*
Access-Control-Allow-Headers: Origin, Accept, Content-Type, Authorization, Access-Control-Allow-Origin
Access-Control-Allow-Origin: *
Content-Type: application/json;charset=UTF-8
DNT: 1
Referer: https://домен1.ру/order.html
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/85.0.4183.121 Safari/537.36 OPR/71.0.3770.234

Response to POST in which the method changes to OPTIONS
Request URL: https://домен2.ру/api/createOrder/
Request Method: OPTIONS
Status Code: 200 
Remote Address: IP(домен2.ру):443
Referrer Policy: no-referrer-when-downgrade
access-control-allow-origin: *
allow: OPTIONS, TRACE, GET, HEAD, POST
content-length: 0
date: Mon, 19 Oct 2020 13:00:09 GMT
public: OPTIONS, TRACE, GET, HEAD, POST
server: Microsoft-IIS/10.0
status: 200
:authority: домен2.ру
:method: OPTIONS
:path: /api/createOrder/
:scheme: https
accept: */*
accept-encoding: gzip, deflate, br
accept-language: ru-RU,ru;q=0.9,en-US;q=0.8,en;q=0.7
access-control-request-headers: access-control-allow-headers,access-control-allow-origin,authorization,content-type
access-control-request-method: POST
origin: https://домен1.ру
referer: https://домен1.ру/order.html
sec-fetch-dest: empty
sec-fetch-mode: cors
sec-fetch-site: <cross-site
user-agent: <Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/85.0.4183.121 Safari/537.36 OPR/71.0.3770.234

Middleware CORS.php
<?php

namespace App\Http\Middleware;

class Cors
{
    public function handle($request, \Closure $next)
    {
        $headers = [
            'Access-Control-Allow-Origin'      => '*',
            'Access-Control-Allow-Methods'     => 'GET, POST, PUT, PATCH, DELETE, OPTIONS',
            'Access-Control-Allow-Credentials' => 'true',
            'Access-Control-Max-Age'           => '86400',
            'Access-Control-Allow-Headers'     => 'Content-Type, Authorization, X-Requested-With, X-Auth-Token, Origin'
        ];

        if ($request->isMethod('OPTIONS'))
        {
            return response()->json('{"method":"OPTIONS"}', 200, $headers);
        }

        $response = $next($request);
        foreach($headers as $key => $value)
        {
            $response->header($key, $value);
        }

        return $response;
    }
}

Routes/api.php
Route::middleware('auth:api')->get('/user', function (Request $request) {
    return $request->user();
});
Route::middleware('cors','auth:api')->group( function () {
    Route::post('/createOrder/', 'API\[email protected]');
});

An intermediary has been added to kernel.php, and according to postman's answers, everything works

Answer the question

In order to leave comments, you need to log in

3 answer(s)
K
khipster, 2016-03-22
@khipster

I suggest not to be smart with regular expressions, but just before this code, check the input string with the fast function strpos for the presence of the mysite.com substring.

V
Vladlen Grachev, 2016-03-22
@gwer

/https?:\/\/(?!mysite.com)\S+\.(png|jpe?g|gif)/

O
OCTAGRAM, 2020-10-29
@OCTAGRAM

Please note: Access-Control-Allow-Origin does not allow the use of an asterisk * for requests with authorization data. There must be exactly the source, as shown above . This is an additional security measure to ensure that the server actually knows who it trusts to make such requests.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question