source

Fetch를 사용하여 x-ww-form-urlencoded 요청을 POST하려면 어떻게 해야 합니까?

lovecheck 2022. 10. 19. 21:13
반응형

Fetch를 사용하여 x-ww-form-urlencoded 요청을 POST하려면 어떻게 해야 합니까?

서버에 폼 인코딩으로 POST 하는 파라미터가 몇 가지 파라미터는 다음과 같습니다.

{
    'userName': 'test@gmail.com',
    'password': 'Password!',
    'grant_type': 'password'
}

요청(현재 매개 변수 없음)을 다음과 같이 보냅니다.

var obj = {
  method: 'POST',
  headers: {
    'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',
  },
};
fetch('https://example.com/login', obj)
  .then(function(res) {
    // Do stuff with result
  }); 

요청에 폼 인코딩된 파라미터를 포함하려면 어떻게 해야 합니까?

다음과 같이 x-www-form-urlencoded payload를 직접 조립해야 합니다.

var details = {
    'userName': 'test@gmail.com',
    'password': 'Password!',
    'grant_type': 'password'
};

var formBody = [];
for (var property in details) {
  var encodedKey = encodeURIComponent(property);
  var encodedValue = encodeURIComponent(details[property]);
  formBody.push(encodedKey + "=" + encodedValue);
}
formBody = formBody.join("&");

fetch('https://example.com/login', {
  method: 'POST',
  headers: {
    'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8'
  },
  body: formBody
})

를 사용하고 있는 경우는,fetch(충분히 현대적인) 브라우저에서는 React Native 대신 오브젝트를 생성하여 본문으로 사용할 수 있습니다.Fetch Standard에는 다음과 같이 기술되어 있습니다.body는 입니다.URLSearchParamsobject를 serialize로 해야 합니다.application/x-www-form-urlencoded단, React Native에서는 이 작업을 수행할 수 없습니다.React Native에서는 이 작업을 수행할 수 없습니다.

한층 더 심플화:

fetch('https://example.com/login', {
    method: 'POST',
    headers:{
      'Content-Type': 'application/x-www-form-urlencoded'
    },    
    body: new URLSearchParams({
        'userName': 'test@gmail.com',
        'password': 'Password!',
        'grant_type': 'password'
    })
});

문서: https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/fetch

사용하다URLSearchParams

https://developer.mozilla.org/en-US/docs/Web/API/URLSearchParams

var data = new URLSearchParams();
data.append('userName', 'test@gmail.com');
data.append('password', 'Password');
data.append('grant_type', 'password');

방금 이 작업을 수행했고 UrlSearchParams가 성공했습니다.이것이 누군가에게 도움이 된다면, 여기 내 코드가 있습니다.

import 'url-search-params-polyfill';
const userLogsInOptions = (username, password) => {



// const formData = new FormData();
  const formData = new URLSearchParams();
  formData.append('grant_type', 'password');
  formData.append('client_id', 'entrance-app');
  formData.append('username', username);
  formData.append('password', password);
  return (
    {
      method: 'POST',
      headers: {
        // "Content-Type": "application/json; charset=utf-8",
        "Content-Type": "application/x-www-form-urlencoded",
    },
      body: formData.toString(),
    json: true,
  }
  );
};


const getUserUnlockToken = async (username, password) => {
  const userLoginUri = `${scheme}://${host}/auth/realms/${realm}/protocol/openid-connect/token`;
  const response = await fetch(
    userLoginUri,
    userLogsInOptions(username, password),
  );
  const responseJson = await response.json();
  console.log('acces_token ', responseJson.access_token);
  if (responseJson.error) {
    console.error('error ', responseJson.error);
  }
  console.log('json ', responseJson);
  return responseJson.access_token;
};

jQuery를 사용할 필요가 없습니다.querystring또는 수동으로 페이로드를 조립합니다. URLSearchParams는 도입방법입니다.다음은 완전한 요구의 예를 들어 가장 간결한 답변의1가지를 나타냅니다.

fetch('https://example.com/login', {
  method: 'POST',
  body: new URLSearchParams({
    param: 'Some value',
    anotherParam: 'Another value'
  })
})
  .then(response => {
    // Do stuff with the response
  });

동일한 기술을 사용하여async/await.

const login = async () => {
  const response = await fetch('https://example.com/login', {
    method: 'POST',
    body: new URLSearchParams({
      param: 'Some value',
      anotherParam: 'Another value'
    })
  })

  // Do stuff with the response
}

네, 네이티브 대신 Axios 또는 다른 HTTP 클라이언트 라이브러리를 사용할 수 있습니다.fetch.

var details = {
    'userName': 'test@gmail.com',
    'password': 'Password!',
    'grant_type': 'password'
};

var formBody = [];
for (var property in details) {
  var encodedKey = encodeURIComponent(property);
  var encodedValue = encodeURIComponent(details[property]);
  formBody.push(encodedKey + "=" + encodedValue);
}
formBody = formBody.join("&");

fetch('http://identity.azurewebsites.net' + '/token', {
  method: 'POST',
  headers: {
    'Accept': 'application/json',
    'Content-Type': 'application/x-www-form-urlencoded'
  },
  body: formBody
})

그것은 나에게 매우 도움이 되고 실수 없이 작동한다.

레퍼런스 : https://gist.github.com/milon87/f391e54e64e32e1626235d4dc4d16dc8

*/ import this statement */
import qs from 'querystring'

fetch("*your url*", {
            method: 'POST',
            headers: {'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8'},
            body: qs.stringify({ 
                username: "akshita",
                password: "123456",
            })
    }).then((response) => response.json())
      .then((responseData) => {
         alert(JSON.stringify(responseData))
    })

npm i querystring --save는 정상적으로 동작합니다.

사용할 수 있습니다.FormData그리고.URLSearchParams로 게시하다application/x-www-form-urlencoded예를 들어 다음과 같습니다.

폼이 있는 경우:

<form>
    <input name="username" type="text" />
    <input name="password" type="password" />
    <button type="submit">login</button>
</form>

아래의 JS를 사용하여 양식을 제출할 수 있습니다.

const form = document.querySelector("form");

form.addEventListener("submit", async () => {
    const formData = new FormData(form);
    try {
        await fetch("https://example.com/login", {
            method: "POST",
            headers: {
                "Content-Type": "application/x-www-form-urlencoded",
            },
            body: new URLSearchParams(formData),
        });
    } catch (err) {
        console.log(err);
    }
});

사용하기만 하면 된다

import  qs from "qs";
 let data = {
        'profileId': this.props.screenProps[0],
        'accountId': this.props.screenProps[1],
        'accessToken': this.props.screenProps[2],
        'itemId': this.itemId
    };
    return axios.post(METHOD_WALL_GET, qs.stringify(data))

JQuery를 사용하는 경우 이 작업도 가능합니다.

fetch(url, {
      method: 'POST', 
      body: $.param(data),
      headers:{
        'Content-Type': 'application/x-www-form-urlencoded'
      }
})

사양에 따르면encodeURIComponent는 일치하는 쿼리 문자열을 제공하지 않습니다.다음과 같이 기술되어 있습니다.

  1. 제어 이름과 값은 이스케이프됩니다.공백 문자는 대체되며 [RFC1738] 섹션 2.2: 영숫자가 아닌 문자는 다음과 같이 이스케이프됩니다.%HH, 퍼센트 기호 및 문자의 ASCII 코드를 나타내는2 자리수의 16 진수입니다.줄 바꿈은 "CR LF" 쌍(즉,%0D%0A).
  2. 제어 이름/값은 문서에 나타나는 순서대로 나열됩니다.이름과 값은 다음과 같이 구분됩니다.=이름/값은 ㄴ/ㄹ 정도로 나누어져 .&.

encodeURIComponent는 공백으로 .%20 아니라, 이에요.+.

로 코드화해야 합니다.encodeURIComponent다른 답변에 나와 있는 방법.

const formUrlEncode = str => {
  return str.replace(/[^\d\w]/g, char => {
    return char === " " 
      ? "+" 
      : encodeURIComponent(char);
  })
}

const data = {foo: "bar߃©˙∑  baz", boom: "pow"};

const dataPairs = Object.keys(data).map( key => {
  const val = data[key];
  return (formUrlEncode(key) + "=" + formUrlEncode(val));
}).join("&");

// dataPairs is "foo=bar%C3%9F%C6%92%C2%A9%CB%99%E2%88%91++baz&boom=pow"

본문을 다음과 같이 설정하기만 하면 됩니다.

var reqBody = "username="+username+"&password="+password+"&grant_type=password";

그리고나서

fetch('url', {
      method: 'POST',
      headers: {
          //'Authorization': 'Bearer token',
          'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
      },
      body: reqBody
  }).then((response) => response.json())
      .then((responseData) => {
          console.log(JSON.stringify(responseData));
      }).catch(err=>{console.log(err)})

http 요청을 전송하거나 대행 수신 요청을 공식화하기 쉬운 react-native-asy-app을 사용할 수 있습니다.

import { XHttp } from 'react-native-easy-app';

* Synchronous request
const params = {name:'rufeng',age:20}
const response = await XHttp().url(url).param(params).formEncoded().execute('GET');
const {success, json, message, status} = response;


* Asynchronous requests
XHttp().url(url).param(params).formEncoded().get((success, json, message, status)=>{
    if (success){
       this.setState({content: JSON.stringify(json)});
    } else {
       showToast(msg);
    }
});

Url Search Params를 사용하여 다음과 같이 toString()을 수행할 수 있습니다.

간단한 방법은 다음과 같습니다.

fetch('https://example.com/login', {
    method: 'POST',
    headers: {
        'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
    },
    body: new UrlSearchParams({
        'userName': 'test@gmail.com',
        'password': 'Password!',
        'grant_type': 'password'
    })
    .toString()
})
.then(res => {
    //Deal with response:
})

에서는, 「」라고 이 있습니다.transformRequest형식 부호화(Form Encoded 。

을 '비교하다'로 했습니다.JSON.stringifyJSON을 사용하다

「」가 .'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'두 경우 모두 Form Encoded 데이터를 전송하고 있다고 주장합니다.

Encoding 은 Form Encoding(폼 ) 기능을 합니다.JSON.stringify.


재갱신:

번째 ★★★★★★★★★★★★★★★★★에서fetch를 들어, 「」를 합니다.bodyJSON 값이 됩니다.

만, 「Form Encoded」를 에,body이 값이 되려면 새 개체를 만들고 Form Encoded 데이터를 해당 개체의 속성으로 설정합니다.

추가 개체를 만들지 마십시오.에 할당해 주세요.body

된 포된 wrapped wrappedfetch

async function post_www_url_encdoded(url, data) {
    const body = new URLSearchParams();
    for (let key in data) {
        body.append(key, data[key]);
    }
    return await fetch(url, { method: "POST", body });
}

const response = await post_www_url_encdoded("https://example.com/login", {
    "name":"ali",
    "password": "1234"});
if (response.ok){ console.log("posted!"); }

Form-Encoded POST 요청을 업로드할 경우 FormData 개체를 사용하는 것이 좋습니다.

코드 예:

var params = {
    userName: 'test@gmail.com',
    password: 'Password!',
    grant_type: 'password'
};

var formData = new FormData();

for (var k in params) {
    formData.append(k, params[k]);
}

var request = {
    method: 'POST',
    headers: headers,
    body: formData
};

fetch(url, request);

언급URL : https://stackoverflow.com/questions/35325370/how-do-i-post-a-x-www-form-urlencoded-request-using-fetch

반응형