ReactJS 코드에서 휴식 후 전화를 거는 방법?
저는 ReactJS와 UI를 처음 접했고 ReactJS 코드에서 간단한 REST 기반 POST 호출을 작성하는 방법을 알고 싶었습니다.
예제가 있으면 실제로 도움이 될 것입니다.
는 직선에서 문서 반응 :
fetch('https://mywebsite.com/endpoint/', {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify({
firstParam: 'yourValue',
secondParam: 'yourOtherValue',
})
})
(이것은 JSON을 게시하지만 multipart-form과 같은 작업을 수행 할 수도 있습니다.)
React는 실제로 REST 호출을 수행하는 방법에 대한 의견이 없습니다. 기본적으로이 작업에 대해 원하는 AJAX 라이브러리를 선택할 수 있습니다.
평범한 오래된 JavaScript를 사용하는 가장 쉬운 방법은 다음과 같습니다.
var request = new XMLHttpRequest();
request.open('POST', '/my/url', true);
request.setRequestHeader('Content-Type', 'application/json; charset=UTF-8');
request.send(data);
최신 브라우저에서는을 사용할 수도 있습니다 fetch
.
REST 호출을 수행하는 컴포넌트가 더있는 경우 컴포넌트에서 사용할 수있는 클래스에 이러한 종류의 로직을 배치하는 것이 좋습니다. 예 :RESTClient.post(…)
또 다른 최근 인기 패키지는 다음과 같습니다 Axios의
설치 : npm install axios --save
간단한 약속 기반 요청
axios.post('/user', {
firstName: 'Fred',
lastName: 'Flintstone'
})
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});
수퍼 에이전트를 설치할 수 있습니다
npm install superagent --save
그런 다음 서버에 전화를 걸려면
import request from "../../node_modules/superagent/superagent";
request
.post('http://localhost/userLogin')
.set('Content-Type', 'application/x-www-form-urlencoded')
.send({ username: "username", password: "password" })
.end(function(err, res){
console.log(res.text);
});
2018 년부터 ReactJS 애플리케이션에 async / await를 통합하는보다 현대적인 옵션이 있습니다. axios와 같은 약속 기반 HTTP 클라이언트 라이브러리를 사용할 수 있습니다. 샘플 코드는 다음과 같습니다.
import axios from 'axios';
...
class Login extends Component {
constructor(props, context) {
super(props, context);
this.onLogin = this.onLogin.bind(this);
...
}
async onLogin() {
const { email, password } = this.state;
try {
const response = await axios.post('/login', { email, password });
console.log(response);
} catch (err) {
...
}
}
...
}
나는이 방법도 정상적인 방법이라고 생각합니다. 하지만 죄송합니다. 영어로 설명 할 수 없습니다 ((
submitHandler = e => {
e.preventDefault()
console.log(this.state)
fetch('http://localhost:5000/questions',{
method: 'POST',
headers: {
Accept: 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify(this.state)
}).then(response => {
console.log(response)
})
.catch(error =>{
console.log(error)
})
}
https://googlechrome.github.io/samples/fetch-api/fetch-post.html
fetch ( 'url / questions', {메소드 : 'POST', 헤더 : {Accept : 'application / json', 'Content-Type': 'application / json',}, 본문 : JSON.stringify (this.state) }). then (응답 => {console.log (응답)}) .catch (error => {console.log (error)})
Here is a the list of ajax libraries comparison based on the features and support. I prefer to use fetch for only client side development or isomorphic-fetch for using in both client side and server side development.
For more information on isomorphic-fetch vs fetch
Here is an example: https://jsfiddle.net/69z2wepo/9888/
$.ajax({
type: 'POST',
url: '/some/url',
data: data
})
.done(function(result) {
this.clearForm();
this.setState({result:result});
}.bind(this)
.fail(function(jqXhr) {
console.log('failed to register');
});
It used jquery.ajax
method but you can easily replace it with AJAX based libs like axios, superagent or fetch.
참고URL : https://stackoverflow.com/questions/38510640/how-to-make-a-rest-post-call-from-reactjs-code
'programing tip' 카테고리의 다른 글
장고와 두 날짜 중에서 선택 (0) | 2020.08.05 |
---|---|
jQuery를 사용하여 동적으로 onClick 이벤트 추가 (0) | 2020.08.05 |
주니어 프로그래머가 시험을 작성하게하는 방법? (0) | 2020.08.05 |
Ruby on Rails에서 DateTime을 간단한 날짜로 변환 (0) | 2020.08.05 |
자바 스크립트에서 대소 문자를 구분하지 않는 정규 표현식 (0) | 2020.08.05 |