如何从 JavaScript 调用 REST Web 服务 API? [英] How to call a REST web service API from JavaScript?

查看:32
本文介绍了如何从 JavaScript 调用 REST Web 服务 API?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个带有按钮的 HTML 页面.当我点击那个按钮时,我需要调用一个 REST Web 服务 API.我试着在网上到处搜索.一点头绪都没有.有人可以给我一个线索/先机吗?非常感谢.

I have an HTML page with a button on it. When I click on that button, I need to call a REST Web Service API. I tried searching online everywhere. No clue whatsoever. Can someone give me a lead/Headstart on this? Very much appreciated.

推荐答案

令我惊讶的是,在撰写本文时,除了 IE11 之外,所有浏览器都支持新的 Fetch API.它简化了您在许多其他示例中看到的 XMLHttpRequest 语法.

I'm surprised nobody has mentioned the new Fetch API, supported by all browsers except IE11 at the time of writing. It simplifies the XMLHttpRequest syntax you see in many of the other examples.

API 包括更多,但从fetch() 方法.它需要两个参数:

The API includes a lot more, but start with the fetch() method. It takes two arguments:

  1. 表示请求的 URL 或对象.
  2. 包含方法、标题、正文等的可选 init 对象

简单的获取:

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
}

重新创建之前的最佳答案,一个帖子:

Recreating the previous top answer, a 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
}

这篇关于如何从 JavaScript 调用 REST Web 服务 API?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆