Your_Uncle_Ostap
@Your_Uncle_Ostap
Учусь премудростям

Как выполнить post запрос с помощью fetch?

ПОСТ запрос к АПИ с помощью Фетч:
getResource = async () => {
        const res = await fetch('https://fan-foto-ml753mfuuq-uc.a.run.app/api/v1/login/access-token', {
            headers: {
                'Accept': 'application/json',
                'Content-Type': 'application/x-www-form-urlencoded',
                'Access-Control-Allow-Methods': 'GET, PUT, POST, DELETE, HEAD, OPTIONS'
                // 'Authorization': 'Bearer TOKEN',

            },
            method: 'POST',
            mode: 'no-cors',
            credentials: 'include',
            body: 'grant_type=&username=charles%40mavencodom&password=test&scope=&client_id=&client_secret='
        });
        // if (!res.ok) {
        //     throw new Error(`Not Fetch, received ${res.status}`)
        // }
        const body = await res.json();
        return body;
    };

Если раскомментировать
if (!res.ok) {
            throw new Error(`Not Fetch, received ${res.status}`)
        }
, тогда всегда срабатывает ИФ и я получаю "Not Fetch, received 0".
А так я получаю "Unhandled Rejection (SyntaxError): Unexpected end of input".
  • Вопрос задан
  • 195 просмотров
Пригласить эксперта
Ответы на вопрос 2
nitrojs
@nitrojs
любитель поасинхронить в ноде
Насколько мне известно, POST запросы не могут иметь body, его нужно передавать в URL запроса:
https://fan-foto-ml753mfuuq-uc.a.run.app/api/v1/login/access-token?grant_type=&username=charles%40mavencodom&password=test&scope=&client_id=&client_secret=
Ответ написан
NeiroNx
@NeiroNx
Программист
getResource = async () => await fetch("/pos",
{
    headers: {
      'Accept': 'application/json',
      'Content-Type': 'application/json'
    },
    method: "POST",
    body: '{"names":"NeiroN"}'
}).then(function(res){
    if (!res.ok) throw Error(`is not ok: ${res.status}`);
    //detect json
    if(res.headers.get("Content-Type").includes("json")){
        return res.json();
    }else{
        return res.text();
   }
}).catch(function(res){
   //Errors
   console.log(res);
   //returned if errors
   return "Error!";
});
Ответ написан
Комментировать
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Войти через центр авторизации
Похожие вопросы