React에서 휴식 후 전화를 거는 방법JS 코드?
React JS와 UI는 처음이라 React에서 간단한 REST 기반 POST 콜을 하는 방법을 알고 싶었습니다.JS 코드
만약 어떤 예가 있다면 그것은 매우 도움이 될 것이다.
React Native 문서에서 직접:
fetch('https://mywebsite.example/endpoint/', {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify({
firstParam: 'yourValue',
secondParam: 'yourOtherValue',
})
})
(이것은 JSON을 투고하고 있습니다만, 예를 들어 멀티파트 폼을 작성할 수도 있습니다).
React Native를 사용하지 않을 경우 ReactJS AJAX FAQ에 대한 문서도 참조하십시오.
리액트는 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);
최신 브라우저에서는 를 사용할 수도 있습니다.
REST 는, EG.E를 참조해 주세요.RESTClient.post(…)
최근에 인기 있는 또 다른 패키지는 다음과 같습니다.
★★★★★★★★★★★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 애플리케이션에 비동기/대기 기능을 통합하는 보다 현대적인 옵션이 제공됩니다.액시오 등의 약속 기반의 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
fetch440url/flash', { 메서드: 'POST', 헤더: { Accept: 'application/json', 'Content-Type': 'application/json', }, 본문: JSON.stringify(this.state) }.그러면(응답 = > {console.log(오류 > {log})}).
다음은 기능 및 지원을 기반으로 한 Ajax 라이브러리 비교 목록입니다.fetch는 클라이언트 측 개발에만 사용하거나, isomific-fetch는 클라이언트 측과 서버 측 개발 모두에서 사용하는 것을 선호합니다.
isomific-fetch vs fetch에 대한 자세한 내용은
다음으로 get과 post의 양쪽 모두에 대해 변경된 util 함수(스택의 다른 포스트)를 나타냅니다.Util.js 파일을 만듭니다.
let cachedData = null;
let cachedPostData = null;
const postServiceData = (url, params) => {
console.log('cache status' + cachedPostData );
if (cachedPostData === null) {
console.log('post-data: requesting data');
return fetch(url, {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify(params)
})
.then(response => {
cachedPostData = response.json();
return cachedPostData;
});
} else {
console.log('post-data: returning cachedPostData data');
return Promise.resolve(cachedPostData);
}
}
const getServiceData = (url) => {
console.log('cache status' + cachedData );
if (cachedData === null) {
console.log('get-data: requesting data');
return fetch(url, {})
.then(response => {
cachedData = response.json();
return cachedData;
});
} else {
console.log('get-data: returning cached data');
return Promise.resolve(cachedData);
}
};
export { getServiceData, postServiceData };
다른 컴포넌트에서의 다음과 같은 사용
import { getServiceData, postServiceData } from './../Utils/Util';
constructor(props) {
super(props)
this.state = {
datastore : []
}
}
componentDidMount = () => {
let posturl = 'yoururl';
let getdataString = { name: "xys", date:"today"};
postServiceData(posturl, getdataString)
.then(items => {
this.setState({ datastore: items })
console.log(items);
});
}
반응하다axios
명령어 사용npm install axios
및 콜post req
method를 지정하면 100개의 요소가 포함된 배열을 반환합니다.
// Define post_req() Method in authAction.js
import axios from 'axios';
const post_req = (data) => {
return new Promise((resolve, reject) => {
const url = 'https://jsonplaceholder.typicode.com/posts'
const header = {
"Access-Control-Allow-Origin": "*",
"Content-Type: application/json"
}
axios({
method: 'post',
url: url,
data: data,
headers: header
});
.then((res)=>{resolve(res);})
.catch((err)=>{reject(err);})
})
}
// Calling post_req() Method in react component
import React, { Component } from 'react';
import { post_req } from 'path of file authAction.js'
class MyReactComponent extends Component {
constructor(props) {
super(props);
this.state = {
myList:[]
};
}
componentDidMount() {
let data = {
.......
}
this.props.post_req(data)
.then((resp)=>{this.setState({myList:resp.data})})
.catch((err)=>{console.log('here is my err',err)})
}
render() {
return (
<div>
....
</div)
}
}
export default MyReactComponent;
'react'에서 React ,{useState} Import, 'axios'에서 Axios Import;
내보내기 기본 함수 Formlp() {
const url ="";
const [state, setstate] = useState({
name:"",
iduser:""
})
function handel(e){
const newdata={...state}
newdata[e.target.id]=e.target.value
setstate(newdata);
}
function submit(e)
{
e.preventDefault();
// Axios.post(url,{name:state.name,iduser:state.iduser}).then( res=>{console.log(res)});
console.log(state)
}
반환(<div onSubmit={ (e)=> submit(e)}> <input onChange={ (e)=> submit(e)}> <input onChange={ (e)=> submit(e)=> handel(e) } id="name" value={state.name} 자리 표시자="type"text" > <input onChange={state.name} } } } ="text"} ="} id="} id="} > id
<button>submit</button>
</form>
</div>
); }
다음은 폼 데이터를 처리하고 데이터를 사용하여 POST 요청을 작성하는 v18+의 간단한 예입니다.
async function handleOrderSubmit(event){
event.preventDefault()
try{
const formData= {name: event.target.name.value, email: event.target.email.value, message: event.target.name.message}
const requestOptions = {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(formData)
};
const response = await fetch('https://www.example.com/form', requestOptions);
const data = await response.json();
navigate("/form-response", { state: {data: data, status: true} })
}
catch(error){
navigate("/form-response", { state: {status: false} })
}
}
주 1: 사용status
'/form-response' 페이지에서 사용자에게 표시할 내용을 사용자 지정할 수 있습니다.참의 경우 다른 섹션을 표시하고 거짓의 경우 다른 섹션을 표시할 수 있습니다.
주의 2: 상태가 정상일 경우 다음 페이지의 데이터에도 액세스하여 사용자 정보에 따라 맞춤화할 수 있습니다.
주 3: event.preventDefault()
페이지를 새로고침하지 않도록 하는 것이 중요합니다.
다음은 예를 제시하겠습니다.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');
});
쓰였다jquery.ajax
Axios, superagent, fetch 등의 AJAX 기반 lib로 쉽게 대체할 수 있습니다.
언급URL : https://stackoverflow.com/questions/38510640/how-to-make-a-rest-post-call-from-reactjs-code
'programing' 카테고리의 다른 글
상위 범위에서 ng 포함 양식의 유효성을 어떻게 확인할 수 있습니까? (0) | 2023.03.28 |
---|---|
응답 가로채기에서 요청을 다시 보내려면 어떻게 해야 하나요? (0) | 2023.03.28 |
JSON을 Flutter로 디코딩하는 방법 (0) | 2023.03.28 |
컨트롤러에서 json 및 xml을 반환하는 스프링 부트 (0) | 2023.03.23 |
Newtonsoft를 사용하여 JSON 어레이를 역직렬화하려면 어떻게 해야 합니까?제이슨 (0) | 2023.03.23 |