回答編集履歴

3

USP

2024/04/10 06:10

投稿

yambejp
yambejp

スコア117632

test CHANGED
@@ -20,3 +20,25 @@
20
20
  ```
21
21
  きょうび、fetchで送るほうが楽だとおもいます。
22
22
  fetchの場合データはformDataで格納すればエンコードも必要ありません
23
+ # 参考
24
+ 参考までにUSP版も
25
+ ```javascript
26
+ const req = new XMLHttpRequest();
27
+ const data={
28
+ grant_type:'authorization_code',
29
+ redirect_uri:'sampleURI',
30
+ code:'sampleCode',
31
+ code_verifier:'sampleVerifierテスト',
32
+ };
33
+ const postData = Object.entries(data).reduce((x,y)=>(x.append(y[0],y[1]),x),new URLSearchParams());
34
+ req.open('POST',restAPIURL);
35
+ req.responseType = 'json';
36
+ req.setRequestHeader("Accept","application/json");
37
+ req.setRequestHeader("cache-control","no-cache");
38
+ req.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
39
+ req.onload = function() {
40
+ console.log(this.response);
41
+ };
42
+ console.log(postData);
43
+ req.send(postData);
44
+ ```

2

調整

2024/04/10 03:18

投稿

yambejp
yambejp

スコア117632

test CHANGED
@@ -1,5 +1,4 @@
1
- XHRでPOSTするならarraybufferを指定してください
1
+ 調整版
2
-
3
2
  ```javascript
4
3
  const req = new XMLHttpRequest();
5
4
  const data={

1

調整

2024/04/10 03:16

投稿

yambejp
yambejp

スコア117632

test CHANGED
@@ -1,13 +1,23 @@
1
1
  XHRでPOSTするならarraybufferを指定してください
2
2
 
3
3
  ```javascript
4
- var xhr = new XMLHttpRequest();
4
+ const req = new XMLHttpRequest();
5
+ const data={
5
- xhr.open('POST', 'example.php');
6
+ grant_type:'authorization_code',
6
- xhr.responseType = 'arraybuffer';
7
+ redirect_uri:'sampleURI',
7
- xhr.onload = function() {
8
+ code:'sampleCode',
8
- };
9
- xhr.send(data);
9
+ code_verifier:'sampleVerifierテスト',
10
10
  };
11
+
12
+ const postData=Object.entries(data).map(x=>`${encodeURIComponent(x[0])}=${encodeURIComponent(x[1])}`).join('&');
13
+ req.open('POST',restAPIURL);
14
+ req.setRequestHeader("Accept","application/json");
15
+ req.setRequestHeader("cache-control","no-cache");
16
+ req.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
17
+ req.onload = function() {
18
+ console.log(JSON.parse(this.response));
19
+ };
20
+ req.send(postData);
11
21
  ```
12
22
  きょうび、fetchで送るほうが楽だとおもいます。
13
23
  fetchの場合データはformDataで格納すればエンコードも必要ありません