Ошибка CORS при реализации post-запроса
Пытаюсь реализовать в своем react-приложении post-запрос через fetch к REST API и получаю ошибку:
Access to fetch at from origin 'http://localhost:4000' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: The 'Access-Control-Allow-Origin' header has a value 'http://83.166.240.63:4000' that is not equal to the supplied origin. Have the server send the header with a valid value, or, if an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.
Сам запрос:
getCatalog(){
let headers = new Headers();
headers.append('Content-Type','application/x-www-form-urlencoded');
headers.append('Accept', 'application/json;text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9');
fetch( apiURL , {
method: "post",
headers: headers,
body: 'action=catalog&contract=1&log='+userLogin+'&pwd='+userPassword+'&user=' + userID,
mode: 'cors',
}).then(r => {
if (r.status === 200)
return r.json().then((data) => {
console.log(data)
})
}).catch(r => console.log(r));
}
Запускаю приложение на сервере через node:
const express = require('express');
const path = require('path');
const app = express();
const port = process.env.PORT || 4000;
app.use(express.static(path.resolve(__dirname, 'build')));
app.get('*', (req, res) => {
res.sendFile(path.resolve(__dirname, 'build', 'index.html'));
});
app.listen(port, () => {
console.info(`Server listening on port ${port}`);
});
Я в курсе что есть решение данной проблемы через 'https://cors-anywhere.herokuapp.com/', однако этот вариант не подходит. Хотелось бы узнать можно ли это как-то нормально решить на фронте или для решения проблемы нужна настройка заголовков ответа бэкэнда (Access-Control)?
Ответы (2 шт):
Вашу ошибку можно решить установив необходимые заголовки на сервере Express, я же могу посоветовать использовать модуль Cors
const express = require('express');
const cors = require('cors'); <------------
const path = require('path');
const app = express();
const port = process.env.PORT || 4000;
app.use(express.static(path.resolve(__dirname, 'build')));
app.use(cors()); <------------
app.get('*', (req, res) => {
res.sendFile(path.resolve(__dirname, 'build', 'index.html'));
});
app.listen(port, () => {
console.info(`Server listening on port ${port}`);
});
CORS работает только если посылать запрос из браузера. Так что решение возможно на общение backend с поставщиком API либо ваш API server должен принимать запросы с прочих ресурсов Access-Control-Allow-Headers: * в заголовке ответа.