Answer the question
In order to leave comments, you need to log in
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"
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
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.
.then(res => res.json())
.then(result => { console.log(result); this.setRes(result) })
.catch(eror => eror);
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 questionAsk a Question
731 491 924 answers to any question