React Native에서 x-www-form-urlencoded 요청 게시
내 서버에 양식 인코딩 된 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
});
요청에 양식 인코딩 매개 변수를 포함하려면 어떻게해야합니까?
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);
다음과 같이 x-www-form-urlencoded 페이로드를 직접 구성해야합니다.
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
대신 기본 반응의 A (충분히 현대) 브라우저에서, 당신은 대신 만들 수 URLSearchParams
때문에, 그 본문으로 개체 및 사용을 표준 가져 오기는 상태 (가) 경우 있음 body
A는 URLSearchParams
개체를 다음과 같이 직렬화한다 application/x-www-form-urlencoded
. 그러나 React Native 에서는URLSearchParams
.
사용하다 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');
더 간단합니다.
body: new URLSearchParams({
'userName': 'test@gmail.com',
'password': 'Password!',
'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;
};
그냥 사용
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))
원래 예제 transformRequest
에는 객체를 Form Encoded 데이터로 변환하는 함수가 있습니다.
In the revised example you have replaced that with JSON.stringify
which converts an object to JSON.
In both cases you have 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
so you are claiming to be sending Form Encoded data in both cases.
Use your Form Encoding function instead of JSON.stringify
.
Re update:
In your first fetch
example, you set the body
to be the JSON value.
Now you have created a Form Encoded version, but instead of setting the body
to be that value, you have created a new object and set the Form Encoded data as a property of that object.
Don't create that extra object. Just assign your value to body
.
If you are using JQuery, this works too..
fetch(url, {
method: 'POST',
body: $.param(data),
headers:{
'Content-Type': 'application/x-www-form-urlencoded'
}
})
According to the spec, using encodeURIComponent
won't give you a conforming query string. It states:
- Control names and values are escaped. Space characters are replaced by
+
, and then reserved characters are escaped as described in [RFC1738], section 2.2: Non-alphanumeric characters are replaced by%HH
, a percent sign and two hexadecimal digits representing the ASCII code of the character. Line breaks are represented as "CR LF" pairs (i.e.,%0D%0A
).- The control names/values are listed in the order they appear in the document. The name is separated from the value by
=
and name/value pairs are separated from each other by&
.
The problem is, encodeURIComponent
encodes spaces to be %20
, not +
.
The form-body should be coded using a variation of the encodeURIComponent
methods shown in the other answers.
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"
*/ 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))
})
After using npm i querystring --save it's work fine.
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
})
it is so helpful for me and works without any error
refrence : https://gist.github.com/milon87/f391e54e64e32e1626235d4dc4d16dc8
참고URL : https://stackoverflow.com/questions/35325370/post-a-x-www-form-urlencoded-request-from-react-native
'program story' 카테고리의 다른 글
신속한 데이터를 16 진수 문자열로 변환하는 방법 (0) | 2020.11.29 |
---|---|
파일에서 생성 될 때 Kubernetes에서 비밀을 업데이트하려면 어떻게해야합니까? (0) | 2020.11.29 |
URL 매개 변수 값 가져 오기 (0) | 2020.11.29 |
좋은 API 또는 나쁜 API를 어떻게 정의합니까? (0) | 2020.11.29 |
사람이 읽을 수있는 형식의 파일 크기 (0) | 2020.11.29 |