各个JavaScript库中相同的POST API调用方法

97 阅读2分钟

我正在使用Insomnia测试一个API,这是一个非常酷的应用程序,可以让你对REST API或GraphQL API服务执行HTTP请求。

他们有一个很好的按钮,可以生成代码,从应用程序中复制一个API请求,在那里你可以直观地设计你的所有请求数据。

在内部,它使用github.com/Kong/httpsn…,这是一个HTTP请求片段生成器,用于许多语言和库,用JavaScript编写。一个非常酷的项目。

总之,出口有几个代码片段。我想在不同的库中展示同一个API调用。

首先,这里是API调用的描述。我向api.randomservice.com 网站(这是我刚想出来的一个随机的URL)发出一个POST请求到/dog 端点。

我向这个端点发送一个有两个属性的对象。

{
  name: 'Roger',
  age: 8
}

编码为JSON。

我还传递一个content-type ,将内容设置为application/json ,并传递一个authorization 头,用我通过API仪表板分配的Bearer token来验证我的请求。

XHR

第一个代码例子是XHR,我们可以在浏览器中本机使用,也可以在Node.js中使用www.npmjs.com/package/xml…

const data = JSON.stringify({
  name: 'Roger',
  age: 8
})

const xhr = new XMLHttpRequest()
xhr.withCredentials = true

xhr.addEventListener('readystatechange', function() {
  if (this.readyState === this.DONE) {
    console.log(this.responseText)
  }
})

xhr.open('POST', 'https://api.randomservice.com/dog')
xhr.setRequestHeader('content-type', 'application/json')
xhr.setRequestHeader('authorization', 'Bearer 123abc456def')

xhr.send(data)

Fetch API

然后我们有相同的代码使用Fetch API,另一个API可以在浏览器中使用,在Node.js中使用www.npmjs.com/package/nod…

fetch('https://api.randomservice.com/dog', {
  method: 'POST',
  headers: {
    'content-type': 'application/json',
    authorization: 'Bearer 123abc456def'
  },
  body: {
    name: 'Roger',
    age: 8
  }
})
  .then(response => {
    console.log(response)
  })
  .catch(err => {
    console.log(err)
  })

node HTTPS模块

接下来是本地的https Node.js模块。

const http = require('https')

const options = {
  method: 'POST',
  hostname: 'api.randomservice.com',
  port: null,
  path: '/dog',
  headers: {
    'content-type': 'application/json',
    authorization: 'Bearer 123abc456def',
    'content-length': '32'
  }
}

const req = http.request(options, res => {
  const chunks = []

  res.on('data', chunk => {
    chunks.push(chunk)
  })

  res.on('end', () => {
    const body = Buffer.concat(chunks)
    console.log(body.toString())
  })
})

req.write(JSON.stringify({ name: 'Roger', age: 8 }))
req.end()

request

下面是使用 requestNode库。

const request = require('request')

const options = {
  method: 'POST',
  url: 'https://api.randomservice.com/dog',
  headers: {
    'content-type': 'application/json',
    authorization: 'Bearer 123abc456def'
  },
  body: { name: 'Roger', age: 8 },
  json: true
}

request(options, (error, response, body) => {
  if (error) throw new Error(error)

  console.log(body)
})

Axios

下面是使用Axios的情况,Axios是Node和浏览器的一个流行库。

const axios = require('axios')

axios.post('https://api.randomservice.com/dog', {
  name: 'Roger', age: 8 
}, {
  headers: {
    'content-type': 'application/json',
    authorization: 'Bearer 123abc456def'
  }
)
.then((res) => {
  console.log(res.data)
})
.catch((error) => {
  console.error(error)
})