-1

I'm creating a react app using the Laravel API and sending requests through Axios but a preflight OPTION request is sent with every GET or POST request
although these preflight requests are not causing me any trouble, I just want to get them out of the way.
I've done enough reading on CORS to know that only simple requests don't need preflight requests, and since my requests contain authorization headers, they are not considered simple.
I've tried:

  1. adding a proxy field to my package.json
  2. creating a middleware for preflight requests
    There was no success with any of the above.
    As far as I can tell, this is the only answer that will work, Why is an OPTIONS request sent and can I disable it?, But I have no idea where to add this header: Access-Control-Allow-Origin: *
    Or I can add this: Access-Control-Max-Age: 600 , Yet again, I'm not sure where it belongs. I mean, I am not sending the option request, so how am I supposed to set headers for something I am not even sending?
    Okay, enough with the explaining, here is my post request:
axios.post(`/ticket/create`, formData).then(res => {
            if (res.status === 201) {
                alert('success')
            } else {
                alert('request failed')
            }
        })

Here are my axios configs:

axios.defaults.baseURL = 'http://127.0.0.1:8000/api';
axios.interceptors.request.use(function (config) {
    const token = localStorage.getItem('auth_token');
    config.headers.Authorization = token ? `Bearer ${token}` : '';
    return config;
})
ZOHRE
  • 35
  • 6
  • Preflight requests are sent by the browser, not React. – Emile Bergeron May 06 '22 at 20:59
  • During development, you could try and serve both the app and the API from the same domain (e.g. `127.0.0.1:8000`), which would no longer trigger CORS flow. – Emile Bergeron May 06 '22 at 21:02
  • 1
    If api and frontend not in same domain you can't get rid of preflight. Without preflight requests your app can be faster so try to host both apps in same domain (subdomains not works) – xuma May 06 '22 at 21:03

0 Answers0