javascriptreactjspostjira-rest-api

React form pass headers to api


I want to post a JSON to a external api from a react form. the api needs headers (username:password) to access it. I wanted to see how I would set up a form to take the inputs of a user and pass it as headers to the api then post some json. I am able to do this with cURL but Im relatively new to react and this has been causing me some problems.


Solution

  • If you are using fetch to make API call you can do something like :

    function signIn(username, password, body) {
        const options = {
            method: method,
            headers: new Headers({username, password}),
            mode: 'no-cors'
        };
    
        options.body = JSON.stringify(body);
    
        fetch(url, options)
        .then(response => response.json())
        .then(data => console.log(data));
    }
    

    You might wanna read more about the same here