フェッチを使用してレスポンスの .json と .text を処理するにはどうすればいいですか? 質問する

フェッチを使用してレスポンスの .json と .text を処理するにはどうすればいいですか? 質問する

jsonを返すAPIを取得していますが、エラーが発生するとテキストのみが返されます(expressのノードでは、結果は で返され.json({})、エラーは で返されます.send('string'))が、APIを変更できない

.catchそこで、JSON を読み取るものを作ろうとしているのですが、それがテキストの場合は、エラーがテキストである場所に入ります。

私が試してみたが成功しなかったことは次のとおりです:

fetch(apiUrl)
    .then(res => {
        try {
            let json = res.json()
            return json
        } catch (error) {
            return new Promise((resolve, reject) => reject(res.text()))
        }
    })
    .then(res => {
        // get result from res.json() **res == res.json**
    })
    .catch(error => {
        // get result from res.text() **res == res.text**
    })

これを達成するにはどうすればいいですか?失敗したら、res.json()次にどうやって入るのでしょうか?.then()res.text().catch

編集.text:インを取りたいのです.catchが、なぜか投げてもres.text()ダメです。

ベストアンサー1

別の方法としては、最初にすべてをテキストにフォーマットし、その後で解析を試み、解析の問題が発生した場合にエラーをスローするという方法があります。

fetch("http://maps.googleapis.com/maps/api/geocode/json?address=google")
    .then(res => res.text())
    .then(body => {
        try {
            return JSON.parse(body);
        } catch {
            throw Error(body);
        }
    })
    .then(console.log)
    .catch(console.error);

fetch("http://maps.googleapis.com/maps/api/geocode/xml?address=google")
    .then(res => res.text())
    .then(body => {
        try {
            return JSON.parse(body);
        } catch {
            throw Error(body);
        }
    })
    .then(console.log)
    .catch(console.error);

おすすめ記事