LoginSignup
1
1

More than 3 years have passed since last update.

JavascriptのFetchをネストして2回リクエストを投げる

Last updated at Posted at 2020-10-12

やりたいこと

大元は、配列から値を1つずつ回してXmlHttpRequestでPOSTを2回やろうと思ってたのですが、なかなかネスト後の値が検知できずにいたところで難しそうだったのでFetchを使ったところうまくネストして2回リクエストを送った値が取得できたのでメモします。化石の知識しかないので過不足は多分結構あります。

コード例

これは例なのでPOSTする先やbody、headerは適宜変更してください。
1回目のリクエスト後にresponseをparseして、使いたい値を取り出してreturnで返すことで次のthenで使うことができます。
これをさらにretuenでfetchを投げることで次のthenで処理できるようにしているという流れになります。(or はJsonで返ってくることを想定したコードです)

fetchNest.js
fetch('http://localhost:8922/services/AdministrationService', {
    method: 'POST',
    body: 'fname=aaaaa&uuid=31963958-31b2-487e-b185-c3559e6bb611&format=XLSX',
    headers: {
        'Content-Type': 'application/x-www-form-urlencoded',
        'Accept': 'text/xml'//or'application/json'
    },
}).then(function(response) {
    return response.text();//or response.json();
}).then(function(responseText) {
    var parser = new DOMParser();//or responseText.dataValue.reportId;
    var doc = parser.parseFromString(responseText, "text/xml");
    return doc.getElementsByTagName("dataValue")[1].textContent;
}).then(function(reportId) {
    return fetch('http://localhost:8922/services/ReportService', {
        method: 'POST',
        body: 'fname=aaaaa&uuid=31963958-31b2-487e-b185-c3559e6bb611&format=XLSX&reportId='+reportId,
        headers: {
            'Content-Type': 'application/x-www-form-urlencoded',
            'Accept': 'text/xml'
        },
    });
}).then(function(response) {
    return response.text();
}).then(function(responseText) {
    console.log(responseText);
}).catch(function(e) {
    // エラーが発生した場合の処理
    console.log(e);
});

大変参考にさせて頂きました

まだXMLHttpRequestを使ってるの? fetchのすすめ
Fetch の使用

1
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1