2016-11-15 2 views
1

私は以下のコードを使用してAPIからデータを取得しています。私はセキュリティで保護された別のAPIを持っており、コンテンツにアクセスするにはユーザー名/パスワードが必要です。同形フェッチモジュールを使用する場合、資格情報を渡す方法がわかりません。助けてもらえますか?同形フェッチ(REDUX/nodeJs) - ユーザー名/パスワードによるPOSTリクエスト

私はこのモジュールを使用しています:https://www.npmjs.com/package/isomorphic-fetch

私は(サンプルcurlコマンド)以下のようにユーザー名とパスワードを渡す必要があり

curl -u admin:hello123 http://test:8765/select?q=* 

コード:ほとんどのAPIを使用します

fetch(
    url 
).then(function (response) { 
    if (response.status != 200) { 
     dispatch(setError(response.status + '===>' + response.statusText + '===>' + response.url)) 
    } 
    return response.json(); 
}).then(function (json) { 
    dispatch(setData(json, q)) 
}).catch(function(err){ 
}); 

答えて

1

認証のためのPOST要求。彼らは、検証するデータ(ユーザー/パスワード)を受け取ることも期待しています。また、送信するデータ(ユーザー/パスワードデータ)の形式(例:application/json)を指定する場合は、通常ヘッダーに余分な情報が必要です。あなたはそれを渡していません。下にあるものが動作するかもしれないことを確認してください。しかし、それはあなたが当てているAPIが何を期待しているかによって異なります(ドキュメントをチェックしてください)。

fetch(url, { 
    method: 'POST', 
    headers: { 
     // Check what headers the API needs. A couple of usuals right below 
     'Accept': 'application/json', 
     'Content-Type': 'application/json' 
    }, 
    body: JSON.stringify({ 
     // Validation data coming from a form usually 
     email: email, 
     password: password 
    } 
}).then(function (response) { 
    if (response.status != 200) { 
     dispatch(setError(response.status + '===>' + response.statusText + '===>' + response.url)) 
    } 
    return response.json(); 
}).then(function (json) { 
    dispatch(setData(json, q)) 
}).catch(function(err){ 
    console.log(err); 
}; 
関連する問題