O
O
OstapO2019-04-11 11:58:37
JavaScript
OstapO, 2019-04-11 11:58:37

How to solve the problem with "CORS policy" when working with the API?

I have a Laravel local project (XAMPP), I make a GET request to a third-party API with the
following code:

const headers = new Headers({
      "Access-Control-Allow-Origin": "*",
      "Access-Control-Allow-Methods": "*",
      "Access-Control-Allow-Headers": "Content-Type, Access-Control-Allow-Headers, Authorization, X-Requested-With",
      'Access-Control-Allow-Credentials': true,
      'Access-Control-Max-Age': '86400',
      'Content-Type': 'application / json; charset=utf8',
      'id': id,
      'token': token
    })
fetch(url, { headers: headers })
      .then(response => response.json())
      .then(data => {
        console.log(data)
      })
      .catch(error => console.error(error))

Query result:
5caf019ce944d913512581.jpeg

Answer the question

In order to leave comments, you need to log in

3 answer(s)
D
DanKud, 2019-04-11
@OstapO

Write a script with an API request in PHP and access it via AJAX.

I
irishmann, 2019-04-11
@irishmann

As far as I understand, Access-Control-Allow-Origin does not solve much through JS, so I used CORS Proxy.

$.ajax({
  type:'POST',
  url: 'https://cors-anywhere.herokuapp.com/http://someproject.ru/api/',
  'data': { 
    query: '{"ask":"'+message+'","userid":'+id+',"key":"1"}'
  },
  'success': function(data){
    msg = JSON.parse(data);
    $(".messages").append('<li><div class="text-msg receive_msg">'+msg['aiml']+'</div></li>');
    while($(".messages li").length > 7){
      $('li:first').detach();
    }
  }
});

I
Ivan Shumov, 2019-04-11
@inoise

For the hundredth time. Cors is a security mechanism against browser client requests. Either the owner of the API allows you access, or you write a server wrapper. Otherwise the browser won't let you

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question