D
D
Dmitriy2021-06-07 16:51:31
AJAX
Dmitriy, 2021-06-07 16:51:31

Why am I getting a CORS error with axios, Vue when making requests to the New Mail API?

You need to contact the new mail API, they have an example with JQuery in the dock

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Title</title>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>

</head>
<body>
<script>
    $(function() {
      var settings = {
        "async": true,
        "crossDomain": true,
        "url": "https://api.novaposhta.ua/v2.0/json/",
        "method": "POST",
        "headers": {
          "content-type": "application/json",
        },
        "processData": false,
        "data": "{\r\n\"apiKey\": \"210d780975bd32f4a027cb5eeb398026\",\r\n \"modelName\": \"Address\",\r\n \"calledMethod\": \"searchSettlements\",\r\n \"methodProperties\": {\r\n \"CityName\": \"васильевка\",\r\n \"Limit\": 5\r\n }\r\n}"
      }

      $.ajax(settings).done(function (response) { console.log(response);
      });
    });

</script>
</body>
</html>

It works, it returns a response, I send requests from Vue SPA using axios, and I get a CORS error.
const response = await axios.post(
      `https://api.novaposhta.ua/v2.0/json/Address/getCities`,
      {
        headers: {
          'Content-Type': 'application/json',
        },
        data: {
          apiKey: '210d780975bd32f4a027cb5eeb398026',
          modelName: 'Address',
          calledMethod: 'getCities',
        },
      },
    );

But I get a CORS error, what am I doing wrong?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
E
Egor Moldavsky, 2021-06-07
@Z3ooM

Try adding to the header

headers: {
          'Content-Type': 'application/json',
           mode: 'cors'
        },

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question