Viewed   4.3k times

I am using React on the front-end and I'm calling API from another domain which I don't own. My axios request:

axios(requestURL, {
        method: 'GET',
        headers: {
            'Access-Control-Allow-Origin': '*',
            'Content-Type': 'application/json',
            'Authorization': key,
            withCredentials: true,
            mode: 'no-cors',
          }

I keep on getting the same error: CORS header ‘Access-Control-Allow-Origin’ missing. Is this something I can overcome from the frontend? I know for a fact that people use that API so it can't be backend fault, right? I tried requesting a lot of APIs and not even one worked with my code. I tried using https://cors-anywhere.herokuapp.com and it worked fine for like a week, I think its down today. I want my site to stay 24/7 so using a proxy is not an option

 Answers

3

You will, unfortunately, need to proxy the request somehow. CORS requests will be blocked by the browser for security reasons. To avoid this, backend needs to inject allow origin header for you.

Solutions depend on where you need to proxy, dev or production.

Development environment or node.js production webserver

The easiest way to do it in this scenario is to use the 'http-proxy-middleware' npm package

const proxy = require('http-proxy-middleware');

module.exports = function (app) {
    app.use(proxy('/api', {
        target: 'http://www.api.com',
        logLevel: 'debug',
        changeOrigin: true
    }));
};

Production - Web server where you have full access Check the following page to see how to enable such proxying on your webserver:

https://enable-cors.org/server.html

Production - Static hosting / Web server without full access

If your hosting supports PHP, you can add a php script like: https://github.com/softius/php-cross-domain-proxy

Then hit a request from your app to the script, which will forward it and inject headers on the response

If your hosting doesn't support PHP Unfortunately, you will need to rely on a solution like the one that you have used.

In order to avoid relying on a third party service, you should deploy a proxy script somewhere that you will use.

My suggestions are:

  • Move to a hosting that supports php :) (Netlify could be a solution, but I'm not sure)

  • You can deploy a node.js based proxy script of your own to Firebase for example (firebase functions), to ensure it will not magically go down, and the free plan could possibly handle your amount of requests.

  • Create a free Amazon AWS account, where you will get the smallest instance for free for a year, and run an ubuntu server with nginx proxy there.

Sunday, September 18, 2022
 
tuanvt
 
1

your server should enable the cross origin requests, not the client. To do this, you can check this nice page with implementations and configurations for multiple platforms

Tuesday, August 9, 2022
 
1

The solution came from a different source, but I post it here to help others looking for the same issue. Basically I used Android AVD (emulator) to build the application. But the emulator is in fact another machine, and that's why it couldn't call the localhost.

To solve the probleme, I had to send the request in the following way:

https://10.0.2.2:3000/v1/test

instead of:

https://localhost:3000/v1/test
Wednesday, October 19, 2022
 
99823
 
4

axios post method takes 3 arguments i.e. url, data & config.

you can structure axios post request as follows:

axios.post(
    'http://rallycoding.herokuapp.com/api/music_albums', 
    {
       'param1': 'value1',
       'param2': 'value2',
       //other data key value pairs
    },
    {
       headers: {
           'api-token': 'xyz',
            //other header fields
       }
    }
);

In your case you need to access https://api.linnworks.net/api/Inventory/GetCategories, which according to docs requires token from auth api in Authorization header. So your GET request via axios will be:

axios.get("https://api.linnworks.net/api/Inventory/GetCategories", { 
    headers: {
      'Authorization': 'token-from-auth-api'
    }
}).then((response) => {
    console.log(response.data);
})
Thursday, September 8, 2022
1

This problem usually related with the backend server, but if you don't have an access to the server so you have two options

First option to use this chrome extension: Allow-Control-Allow-Origin but unfortunately this extension is not available in the other browsers so you need to use

Second option by using online CORS proxy like

https://cors-anywhere.herokuapp.com/http://example.com

http://cors-proxy.htmldriven.com/?url=http://www.htmldriven.com/sample.json

CORS proxy is a free service for developers who need to bypass same-origin policy related to performing standard AJAX requests to 3rd party services.

Here's an example of Axiox call using CORS proxy

const urlProxy = 'https://cors-anywhere.herokuapp.com/http://example.com';
export function post() {
    let users = {
        username: '',
        password: '',
    };
    return axios({
            method:'POST',
            url:urlProxy,
            data: users, // Delete it if you dont have a data
            withCredentials: true, // Delete it if your request doesn't required credentials
            headers: {
                'Accept': 'application/json',
                'Content-Type': 'application/json'
                'Origin': '*',
                'Access-Control-Allow-Headers': '*',
                'Access-Control-Allow-Origin': '*',
            }
        })

            .then(function (response) {
                console.log(response);
            })
            .catch(function (error) {
                console.log(error);
            })
}

I added withCredentials() it makes your browser include cookies and authentication headers in your XHR request. If your service depends on any cookie (including session cookies), it will only work with this option set.

There's a Firefox extension that adds the CORS headers to any HTTP response working on the latest Firefox (build 36.0.1) released March 5, 2015 Check out this link

Hope this will help you

Wednesday, November 2, 2022
 
Only authorized users can answer the search term. Please sign in first, or register a free account.
Not the answer you're looking for? Browse other questions tagged :