S
S
Seraphim2019-09-25 11:44:31
OAuth
Seraphim, 2019-09-25 11:44:31

How to correctly write a component that will send a cross-domain request and save the token in the state?

I'm solving a test task, I can't find an error, either the component wrote it wrong, or the request is a curve. It is unlikely that it will be possible to complete the task by the deadline, but I really want to understand the issue.
First you need to get a token, but there were problems with these.
Here is the description of the request attached to the assignment:

curl -X POST "<host>/oauth/token" 
     -H "Authorization: Basic NDk0NTU5Mjg5OTM0MzYwOlFNMUpaQ0pUMFNLMUw3NQ==" 
     -d "grant_type=password" 
     -d "[email protected]" 
     -d "password=admin" 
     -d "scope=trust"
     -d "session_key=somesessionkey"

Actually, my code is:
import * as React from 'react';

const BASE_PATH = 'url'; // здесь адрес api компании, не знаю, могу ли я его публично показывать
const data = 'grant_type=password&[email protected]&password=admin&scope=trust&session_key=123';

class GetApi extends React.Component {

    state = {
        result: {}
    };

    componentDidMount(): void {
        fetch(`${BASE_PATH}/oauth/token`,
            {
                method: 'POST',
                mode: 'cors',
                credentials: "include",
                headers: {
                    "Authorization": 'Basic NDk0NTU5Mjg5OTM0MzYwOlFNMUpaQ0pUMFNLMUw3NQ==',
                    "Content-type": 'application/x-www-form-urlencoded'
                },
                body: data
            })
            .then(res => res.json())
            .then(result => this.setRes(result))
            .catch(eror => eror);
    }

    setRes = result => {
        this.setState({ result });
    };

    render () {
        const { result } = this.state;
        console.log(result);
        return (
            <h1>{ result }</h1>
        );
    }

}

export default GetApi;

Answer the question

In order to leave comments, you need to log in

2 answer(s)
S
Sunflowerz, 2019-09-25
@Sunflowerz

I highly recommend installing postman first.
Then remember this program for the rest of your life.
Then enter all the input data in postman, find the error in the headers. Then write to the state token.

H
hzzzzl, 2019-09-25
@hzzzzl

.then(res => res.json())
  .then(result => { console.log(result); this.setRes(result) })
  .catch(eror => eror);

does it work without error? in response exactly comes json, and not text, for example?
this.setState({ result });
..
const { result } = this.state;  
console.log(result);   // здесь что-то есть?

console.log(this.state) // ключ в стейте называется result?

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question