2

I'm developing a VueJS application which makes calls to an external API. When I do this:

this.$http.get(myAPIurl)
                .then(response => {
                    return response.json();
                })
                .then(data => {
                    console.log(data);
                }); 

I get these 2 errors in chrome console.

Refused to set unsafe header "Access-Control-Request-Method"

XMLHttpRequest cannot load http://xxxxxx Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:8080' is therefore not allowed access

How do I go about it?

splunk
  • 6,435
  • 17
  • 58
  • 105
  • What is server for your backend API- myAPIurl – Saurabh Nov 25 '16 at 08:50
  • @saurabh I'm using musixmatch API, so it's a third party server. – splunk Nov 25 '16 at 08:57
  • Possible duplicate of [XMLHttpRequest cannot load XXX No 'Access-Control-Allow-Origin' header](https://stackoverflow.com/questions/35553500/xmlhttprequest-cannot-load-xxx-no-access-control-allow-origin-header) – Quentin Feb 11 '19 at 23:06

1 Answers1

0

If you are doing an XMLHttpRequest to a different domain than your page is on, your browser will block it as it usually allows a request in the same origin for security reasons. You need to do something different when you want to do a cross-domain request. A tutorial about how to achieve that is Using CORS.

When you are using postman they are not restricted by this policy. Quoted from Cross-Origin XMLHttpRequest:

Regular web pages can use the XMLHttpRequest object to send and receive data from remote servers, but they're limited by the same origin policy. Extensions aren't so limited. An extension can talk to remote servers outside of its origin, as long as it first requests cross-origin permissions.

To solve this, your external API server has to support cors request by setting following headers:

header('Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type, Accept');

Edited

You can use format as jsonp, like it is being done in this codepen. Here is discussion on how to use jsonp with vue-resource, see sample code from this link:

this.$http.jsonp('https://api.instagram.com/v1/tags/' + this.hash + '/media/recent', {
    client_id: 'xxxxxxxxxxxxxxxxxxxxxxxx'
}, function(data){
    this.pictures = _map(data.data, this.transFormInstagramModelToLocalModel);
}, {
    'jsonp': 'callback'
});

You can find discussions here also helpful.

Saurabh
  • 71,488
  • 40
  • 181
  • 244