utils.js 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. /*
  2. * Copyright (C) 2020 Tencent Cloud.
  3. *
  4. * Licensed under the Apache License, Version 2.0 (the "License");
  5. * you may not use this file except in compliance with the License.
  6. * You may obtain a copy of the License at
  7. *
  8. * http://www.apache.org/licenses/LICENSE-2.0
  9. *
  10. * Unless required by applicable law or agreed to in writing, software
  11. * distributed under the License is distributed on an "AS IS" BASIS,
  12. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. * See the License for the specific language governing permissions and
  14. * limitations under the License.
  15. */
  16. 'use strict';
  17. const axios = require('axios');
  18. const { region } = require('./config');
  19. const { sign } = require('../common');
  20. /**
  21. * 请求腾讯云OCR接口公共方法
  22. * @param {string} action - 接口请求action
  23. * @param {object} payload - 接口请求体
  24. * @returns {object} API返回的有效数据
  25. */
  26. async function request(action, payload) {
  27. const [timestamp, authorization] = sign('ocr', JSON.stringify(payload));
  28. const options = {
  29. url: 'https://ocr.tencentcloudapi.com',
  30. method: 'POST',
  31. headers: {
  32. 'Content-Type': 'application/json',
  33. 'X-TC-Action': action,
  34. [region ? 'X-TC-Region' : '']: region,
  35. 'X-TC-Version': '2018-11-19',
  36. 'X-TC-Timestamp': timestamp,
  37. Authorization: authorization
  38. },
  39. data: payload
  40. };
  41. const response = await axios(options);
  42. const { status, statusText, data } = response;
  43. if (status !== 200) {
  44. throw new Error(`${action}接口调用失败[${status} - ${statusText}]`);
  45. }
  46. if (data.Response.Error) {
  47. throw new Error(data.Response.Error.Message);
  48. }
  49. return data.Response;
  50. }
  51. module.exports = { request };