JavaScript에서 REST 웹 서비스 API를 호출하는 방법은 무엇입니까?
버튼이있는 HTML 페이지가 있습니다. 해당 버튼을 클릭하면 REST 웹 서비스 API를 호출해야합니다. 나는 모든 곳에서 온라인 검색을 시도했다. 단서가 없습니다. 누군가 나에게 이것에 대해 리드 / 헤드 스타트를 줄 수 있습니까? 대단히 감사합니다.
글을 쓰는 시점에 IE11을 제외한 모든 브라우저에서 지원되는 새로운 Fetch API를 언급 한 사람이 아무도 없습니다. 다른 많은 예제에서 볼 수있는 XMLHttpRequest 구문을 단순화합니다.
API에는 훨씬 더 많은 것이 포함되어 있지만 fetch()
메소드 부터 시작하십시오 . 두 가지 주장이 필요합니다.
- 요청을 나타내는 URL 또는 객체입니다.
- 메소드, 헤더, 본문 등을 포함하는 선택적 init 객체
간단한 GET :
const userAction = async () => {
const response = await fetch('http://example.com/movies.json');
const myJson = await response.json(); //extract JSON from the http response
// do something with myJson
}
이전의 최상위 답변 인 POST를 다시 작성하십시오.
const userAction = async () => {
const response = await fetch('http://example.com/movies.json', {
method: 'POST',
body: myBody, // string or object
headers: {
'Content-Type': 'application/json'
}
});
const myJson = await response.json(); //extract JSON from the http response
// do something with myJson
}
자바 스크립트 :
function UserAction() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
alert(this.responseText);
}
};
xhttp.open("POST", "Your Rest URL Here", true);
xhttp.setRequestHeader("Content-type", "application/json");
xhttp.send("Your JSON Data Here");
}
버튼 동작 ::
<button type="submit" onclick="UserAction()">Search</button>
자세한 내용은 다음 링크를 참조하십시오 (2017/01/11 업데이트)
다음은 json을 사용한 인증을 사용하는 또 다른 Javascript REST API 호출입니다.
<script type="text/javascript" language="javascript">
function send()
{
var urlvariable;
urlvariable = "text";
var ItemJSON;
ItemJSON = '[ { "Id": 1, "ProductID": "1", "Quantity": 1, }, { "Id": 1, "ProductID": "2", "Quantity": 2, }]';
URL = "https://testrestapi.com/additems?var=" + urlvariable; //Your URL
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = callbackFunction(xmlhttp);
xmlhttp.open("POST", URL, false);
xmlhttp.setRequestHeader("Content-Type", "application/json");
xmlhttp.setRequestHeader('Authorization', 'Basic ' + window.btoa('apiusername:apiuserpassword')); //in prod, you should encrypt user name and password and provide encrypted keys here instead
xmlhttp.onreadystatechange = callbackFunction(xmlhttp);
xmlhttp.send(ItemJSON);
alert(xmlhttp.responseText);
document.getElementById("div").innerHTML = xmlhttp.statusText + ":" + xmlhttp.status + "<BR><textarea rows='100' cols='100'>" + xmlhttp.responseText + "</textarea>";
}
function callbackFunction(xmlhttp)
{
//alert(xmlhttp.responseXML);
}
</script>
<html>
<body id='bod'><button type="submit" onclick="javascript:send()">call</button>
<div id='div'>
</div></body>
</html>
$("button").on("click",function(){
//console.log("hii");
$.ajax({
headers:{
"key":"your key",
"Accept":"application/json",//depends on your api
"Content-type":"application/x-www-form-urlencoded"//depends on your api
}, url:"url you need",
success:function(response){
var r=JSON.parse(response);
$("#main").html(r.base);
}
});
});
기다릴 add (this.readyState == 4 && this.status == 200)가 더 좋다고 생각합니다.
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
// Typical action to be performed when the document is ready:
var response = xhttp.responseText;
console.log("ok"+response);
}
};
xhttp.open("GET", "your url", true);
xhttp.send();
일반적인 방법은 PHP와 ajax를 사용하는 것입니다. 그러나 귀하의 요구 사항에 따라 아래에서 정상적으로 작동합니다.
<body>
https://www.google.com/controller/Add/2/2<br>
https://www.google.com/controller/Sub/5/2<br>
https://www.google.com/controller/Multi/3/2<br><br>
<input type="text" id="url" placeholder="RESTful URL" />
<input type="button" id="sub" value="Answer" />
<p>
<div id="display"></div>
</body>
<script type="text/javascript">
document.getElementById('sub').onclick = function(){
var url = document.getElementById('url').value;
var controller = null;
var method = null;
var parm = [];
//validating URLs
function URLValidation(url){
if (url.indexOf("http://") == 0 || url.indexOf("https://") == 0) {
var x = url.split('/');
controller = x[3];
method = x[4];
parm[0] = x[5];
parm[1] = x[6];
}
}
//Calculations
function Add(a,b){
return Number(a)+ Number(b);
}
function Sub(a,b){
return Number(a)/Number(b);
}
function Multi(a,b){
return Number(a)*Number(b);
}
//JSON Response
function ResponseRequest(status,res){
var res = {status: status, response: res};
document.getElementById('display').innerHTML = JSON.stringify(res);
}
//Process
function ProcessRequest(){
if(method=="Add"){
ResponseRequest("200",Add(parm[0],parm[1]));
}else if(method=="Sub"){
ResponseRequest("200",Sub(parm[0],parm[1]));
}else if(method=="Multi"){
ResponseRequest("200",Multi(parm[0],parm[1]));
}else {
ResponseRequest("404","Not Found");
}
}
URLValidation(url);
ProcessRequest();
};
</script>
웹 사이트의 프런트 엔드에 무언가를 배치하기 전에 API 연결을 열어 보겠습니다. 파일을 열고 HTTP 요청을하는 방법 인 XMLHttpRequest 객체를 사용합니다.
We'll create a request variable and assign a new XMLHttpRequest object to it. Then we'll open a new connection with the open() method - in the arguments we'll specify the type of request as GET as well as the URL of the API endpoint. The request completes and we can access the data inside the onload function. When we're done, we'll send the request.
// Create a request variable and assign a new XMLHttpRequest object to it. var request = new XMLHttpRequest()
// Open a new connection, using the GET request on the URL endpoint
request.open('GET', 'https://ghibliapi.herokuapp.com/films', true)
request.onload = function () {
// Begin accessing JSON data here
}
}
// Send request
request.send()
참고URL : https://stackoverflow.com/questions/36975619/how-to-call-a-rest-web-service-api-from-javascript
'Programming' 카테고리의 다른 글
아파치 스파크 : map vs mapPartitions? (0) | 2020.07.18 |
---|---|
Windows 배치 스크립트에서“@”의 의미 (0) | 2020.07.18 |
Objective-C에서 객체를 캐스팅하는 방법 (0) | 2020.07.18 |
제네릭 메서드 다중 (OR) 형식 제약 조건 (0) | 2020.07.17 |
C ++ 성능 문제 : 정수에서 std :: string으로의 변환 (0) | 2020.07.17 |