IT이야기

가져오기 요청에서 POST 매개 변수를 전달하는 방법 - 기본 반응

cyworld 2022. 3. 27. 14:19
반응형

가져오기 요청에서 POST 매개 변수를 전달하는 방법 - 기본 반응

이건 내 암호야

componentWillMount() {
  fetch("http://localmachine/localservice/webservice/rest/server.php", {
    method: 'POST',
    body: JSON.stringify({
      wstoken: 'any_token',
      wsfunction: 'any_function',
      moodlewsrestformat: 'json',
      username: 'user',
      password: 'pass',
    })
  })
  .then((response) => response.text())
  .then((responseText) => {
    alert(responseText);
  })
  .catch((error) => {
    console.error(error);
  });
}

브라우저에서는 이 요청이 토큰을 반환하지만, 내 반응형 안드로이드 앱에서는 xml 오류를 반환한다.

이것이 나에게 효과가 있었다.

fetch("http://10.4.5.114/localservice/webservice/rest/server.php", {
  method: 'POST',
  headers: new Headers({
             'Content-Type': 'application/x-www-form-urlencoded', // <-- Specifying the Content-Type
    }),
  body: "param1=value1&param2=value2" // <-- Post parameters
})
.then((response) => response.text())
.then((responseText) => {
  alert(responseText);
})
.catch((error) => {
    console.error(error);
});

사후 요청에 헤더를 추가해 보십시오.

       headers: {
         'Accept': 'application/json',
         'Content-Type': 'application/json',

       },
       body: JSON.stringify({
         wstoken: 'any_token',
         wsfunction: 'any_function',
         moodlewsrestformat: 'json',
         username: 'user',
         password: 'pass',
      })

참조URL: https://stackoverflow.com/questions/42011100/how-can-i-pass-post-parameters-in-fetch-request-react-native

반응형