javascript 请求客户端Sample.js

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了javascript 请求客户端Sample.js相关的知识,希望对你有一定的参考价值。

import axios from 'axios'

import config from '../config'
import {getUserIdToken} from './auth'

const axiosInstance = axios.create({
  baseURL: config.api[process.env.NODE_ENV].base + config.api[process.env.NODE_ENV].graphqlEndpoint,
  timeout: 5000
})

axiosInstance.defaults.headers.post['Content-Type'] = 'application/json'

export default class RequestClient {
  static combineQueries (args) {
    const queries = Array.from(args).map(q => q.trim().slice(1, -1))
    const queryString = `{ ${queries.join('')} }`

    return queryString
  }

  static async mutate () {
    axiosInstance.defaults.headers.common['012-User-Token'] = await this.setAuthorization()

    return axiosInstance.post('', {
      query: `mutation ${this.combineQueries(arguments)}`
    })
  }

  static async query () {
    axiosInstance.defaults.headers.common[config.auth.headerName] = await this.setAuthorization()

    return axiosInstance.post('', {
      query: `query ${this.combineQueries(arguments)}`
    })
  }

  static setAuthorization () {
    return new Promise((resolve, reject) => {
      getUserIdToken()
        .then(token => {
          resolve(token)
        })
        .catch(error => {
          console.log('Error retrieving token - ', error)
          reject(error)
        })
    })
  }
}

以上是关于javascript 请求客户端Sample.js的主要内容,如果未能解决你的问题,请参考以下文章

javascript 终极版,sample.js

javascript 工作者线程,sample3.js

如何在“onclick”事件期间加载外部Javascript文件?

可以从 http(javascript 客户端)直接向 Amazon SQS 发送请求吗?

如何使用客户端Javascript向Ldap发出请求?

Javascript之运行原理探究