0

I can get my data with fetch

 let myHeaders = new Headers();
        myHeaders.append('X-Auth-Token', token,);
        myHeaders.append('Content-Type', 'application/json');      
            fetch("myUrl", {
            withCredentials: true,
            headers: myHeaders
            }).then(function (response) {
                console.log(response)
            })

but fetching data is not working with axios. this is my axios code

  const headers={
            'X-Auth-Token': token,
            "content-type":"application/json"
        }
        axios.get('myUrl',{headers:headers,withCredentials:true})
            .then(response => {
                console.log(response)
            })
            .catch(err => {
                console.log(err)
            });
ali mottaghian
  • 310
  • 1
  • 4
  • 11
  • what do you mean not working? show the error please – Naor Tedgi Jan 02 '19 at 17:42
  • (this is the error). The value of the 'Access-Control-Allow-Origin' header in the response must not be the wildcard '*' when the request's credentials mode is 'include'. The credentials mode of requests initiated by the XMLHttpRequest is controlled by the withCredentials attribute. – ali mottaghian Jan 03 '19 at 06:58

1 Answers1

0

I use it this way:

Check if your headers object is in good shape with a console log.

const headers = {
        'X-Auth-Token': token,
        'content-type': 'application/json'
    };
console.log(headers);
const request = axios.create({
    myUrl,
    headers: myHeaders,
    withCredentials: true
})


request.get() // If you add a string inside the brackets it gets appended to your url
    .then(res => console.log(res))
    .catch(err => console.log(err))

If the error you are getting is about CORS (Cross Origin Resource Sharing):

If you want to allow credentials then your Access-Control-Allow-Origin must not use *. You will have to specify the exact protocol, domain, port.

You need to set the server to allow your origin.

It's a very common problem and you will see it happen often. Read more about cors here:

https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS

https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Access-Control-Allow-Origin

Nikola
  • 981
  • 1
  • 10
  • 20