Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Axios with Vue access http instead of https

Tags:

vue.js

axios

I am using vue2 and axios to make my ajax calls. In a page I am calling various ajax calls, some go as HTTPS while others go through HTTP, although both codes are similar.

Example:

        axios.get('/api/' + app.$variable1 + '/get-something/')
        .then(({ data }) =>
        {
            app.array = [];

            for(let i = 0; i < data.length; i++)
            {
                app.vats.push({
                    id:data[i]['id'],
                    name:data[i]['name'],
                    something_else[i]['something_else']
                });
            }
        })

Question: How can I force Axios to take HTTPS?

Objs: I cannot manually add https, as such: "https://www.example.com/1234/12" because I am using relative urls (I have certain id's assigned at url, and reuse them to make my calls).

Server: 1) I am forcing Https through htaccess 2) I am also using Secure Headers which does not allow the browser to get out of "self"

EDIT:

So trying to get down to the issue: 1) In the Mounted method I am calling 4 individual API's. The first two fail due to HTTP, and the last two get through. I tried chaning the order, and its always the first two to fail. I tried to move the code to Created, which makes less sense, and sure enough it did not work.

HELP!!

like image 442
Abhishek Shah Avatar asked Sep 21 '18 12:09

Abhishek Shah


1 Answers

Add an Axios request interceptor and change the config.url from http to https. All requests will be intercepted and you will have access to the base URL scheme.

  const instance = axios.create({
    baseURL: 'http://api.com',
  })

  instance.interceptors.request.use(function(config) {
    // change the url scheme from http to https
    config.url = config.url.replace('http://', 'https://')

    return config
  })
like image 142
David Kyle Avatar answered Oct 07 '22 00:10

David Kyle



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!