Исправлен запрос 'cors' между разными локальными хостами. 405 (метод не разрешен) - PullRequest
0 голосов
/ 12 мая 2018

Я использую следующий код для запроса файла:

function getData(imageEndpoint) {
  return fetch(imageEndpoint, {
    mode: 'cors'
  })
    .then(response => {
      console.log(response);
    })
    .then(data => {
      if (!('caches' in window)) {
        return caches.open(cacheName)
        .then(cache => {
          return cache.put(imageEndpoint, data);
        });
      }
      return data;
    })
    .catch(e => {
      console.log('Request issue, ', e);
    });
}

Что выводится в следующем сообщении об ошибке:

Failed to load http://localhost:7000/image.jpg: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:8080' is therefore not allowed access. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.

P.S Сервер работает на :8000

Когда я добавляю заголовок cors

  return fetch(imageEndpoint, {
    mode: 'cors',
    headers: {
      'Access-Control-Allow-Origin': '*'
    }
  })

Следующая ошибка:

http://localhost:7000/image.jpg 405 (Method Not Allowed)

index.html:1 Failed to load http://localhost:7000/image.jpg: 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. The response had HTTP status code 405. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.

Подскажите, пожалуйста, как настроить запрос, чтобы успешно получить файл?

1 Ответ

0 голосов
/ 12 мая 2018

вам нужно иметь заголовок Access-Control-Allow-Origin: URL Here или Access-Control-Allow-Origin: * как в ответе OPTIONS, так и в ответе POST. Вы также должны включить заголовок Access-Control-Allow-Credentials: true в ответ POST.

Ваш ответ OPTIONS должен также включать заголовок Access-Control-Allow-Headers: origin, content-type, accept, чтобы соответствовать запрошенному заголовку.

...