node.jspostreduxisomorphic-fetch-api

Isomorphic fetch (REDUX / nodeJs) - POST request with username / password


I am using the below code to get the data back from API and it works fine. I have another API which is secured one and that requires a user name / password to access the content and I am not sure how to pass in the credentials when using isomorphic fetch module. Can someone help?

I am using this module: https://www.npmjs.com/package/isomorphic-fetch

I need to pass in username and password as below (Sample curl command)

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

Code:

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){
});

Solution

  • Most APIs would used a POST request for authentication. They expect as well to receive the data to validate (user/password). Also, they usually require extra information in the header like to specify the format (e.g. application/json) of the data (the user/password data) you are sending. You are not passing any of that. Check below something that might work, but it all depends of what the API you are hitting is expecting (check its documentation).

    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);
    };