Y
Y
yaroslavklimuk2021-06-20 21:23:32
JavaScript
yaroslavklimuk, 2021-06-20 21:23:32

Access to fetch has been blocked by CORS policy, error in request or server?

It is necessary to send data from the form to the server and receive a response. There is no access to the server.
On test api ( https://jsonplaceholder.typicode.com/ ) everything works, I send, I receive and everything is fine. But on the one I need I get an error. What could be the problem?
60cf871be270c094304054.png

Request code

const requestURL = 'https://your-url.com';

function sendRequest(method, url, body) {
  const headers = {
    'Content-Type': 'application/x-www-form-urlencoded',
  };
  return fetch(url,
    {
      method,
      body,
      headers,
    }).then((response) => {
    if (response.ok) {
      return response.text();
    }
    return response.text().then((error) => {
      const err = new Error();
      err.data = error;
      throw err;
    });
  });
}
const form = document.getElementById('form');

form.addEventListener('submit', (e) => {
  e.preventDefault();
  const formData = new FormData(form);
  const values = Object.fromEntries(formData.entries());
  sendRequest('POST', requestURL, JSON.stringify(values))
    .then((data) => console.log(data))
    .catch((err) => console.log(err));
  // sendRequest('GET', requestURL, null)
  // 	.then((data) => console.log(data))
  // 	.catch((err) => console.log(err));
});

Answer the question

In order to leave comments, you need to log in

1 answer(s)
4
4X_Pro, 2021-06-20
@XXXXPro

The server should issue the Access-Control-Allow-Origin header, where it indicates which sites it can be accessed from using fetch. Test APIs most likely have Access-Control-Allow-Origin: *, which is why everything works for them.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question