1

I am stumbled upon a problem, perhaps some one can help. Currently i have installed axios via npm in react project and while sending a request to node backend i am getting the following error

Access to XMLHttpRequest at 'http://mechanicapp.test:3333/api/manufacturer?pagination=true&perPage=3' from origin 'http://localhost:3000' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: The 'Access-Control-Allow-Origin' header contains the invalid value 'false'.

I have read earlier stack overflow post on this concern but none of them solve my problem.

i have tried to set Access-Control-Allow-Origin in the header of request but it did not help.

w.Header().Set("Access-Control-Allow-Origin", "*")

I am using Adonis.js Framework for my backend, I am wondering if some on can help me out.

My code for sending request is as follows,perhaps it can help you in solving the query.


function checkAuthTokenExclusion(arr, url) {
    return (arr.indexOf(url) != -1);
}

let responseFormat = {
    error: false,
    response: {},
}

/*exclusion array, add those url to this array for which you dont want to set token in header*/
var exclusion = ['user-login'];

const axiosRequest = () => {
    const defaultOptions = {
        baseURL: "http://mechanicapp.test:3333/api/",
        /*  method: 'get',*/
        headers: {
            'Content-Type': 'application/json',
        },
    };

    // Create instance
    let instance = axios.create(defaultOptions);

    // Set the AUTH token for any request
    instance.interceptors.request.use(function (config) {

        /*the token will be added to header for those url which are not found in the exclusion array*/
        if (!checkAuthTokenExclusion(exclusion, config.url)) {
            const token = localStorage.getItem('fixlo-access-token');
            config.headers.Authorization = token ? `Bearer ${token}` : '';
        }
        return config;
    });

    return instance;
};


async function makeRequest(requestType = 'get', url, data = {},optionalConfig = {}) {

    let requestObj = null;

    switch (requestType) {
        case 'get':

            /*sample params pass code for get requests*/

            /*
                axiosRequest().get('/', {
                    params: {
                        results: 1,
                        inc: 'name,email,picture'
                    }
            });*/

            requestObj = axiosRequest().get(url, data);
            break;

        case 'post':
            requestObj = axiosRequest().post(url, data,optionalConfig);
            break;

        case 'put':
            requestObj = axiosRequest().put(url, data,optionalConfig);
            break;

        case 'delete':
            requestObj = axiosRequest().delete(url, data);
            break;

        default:
            /*if no params matches in switch case*/
            requestObj = axiosRequest().get(url, data);

    }




   await requestObj.then(callResponse => {
        /*success*/
        responseFormat.response = callResponse.data;
    }).catch(error => {
        /*error*/
        responseFormat.error = true;
        responseFormat.response = error.response.data;
    });



    return responseFormat;

}


// export default axiosRequest();
export default makeRequest;```


 

1 Answers1

0

Cross-Origin Resource Sharing (CORS) is a way to allow incoming HTTP requests from different domains. It is very common in AJAX applications where the browser blocks all cross-domain requests if the server does not authorize them. So to solve your query, your server should enable the cross origin requests, not the client.

Adonis.js give built in feature to turn the CORS on and off,turning it on will let your server start accepting requests from cross origins.

To do so, simply in your adonis server directory

  1. Go to your config directory.
  2. Find cors.js and change origin from false to true

Your server should know start accepting request from cross origins.

You can read more here at https://adonisjs.com/docs/4.1/cors

Saddam
  • 1,174
  • 7
  • 14