微前端nuxt3.0方便请求api可封装一个使用哈希算法出key值的http,http封装
    		       		warning:
    		            这篇文章距离上次修改已过433天,其中的内容可能已经有所变动。
    		        
        		                
                在Nuxt 3中,你可以创建一个可重用的HTTP客户端来封装HTTP请求逻辑。以下是一个使用哈希算法生成key的简单例子:
首先,安装cross-fetch,因为Nuxt 3中不包含全局的fetch:
npm install cross-fetch然后,创建一个http.js文件来封装HTTP请求:
// http.js
import { createHash } from 'crypto';
import fetch from 'cross-fetch';
 
const generateKey = (url, method, body) => {
  const hash = createHash('sha256');
  hash.update(url);
  hash.update(method);
  hash.update(body || '');
  return hash.digest('hex');
};
 
const httpClient = async (url, options = {}) => {
  const { method = 'GET', body } = options;
  const key = generateKey(url, method, body);
 
  try {
    const response = await fetch(url, { method, body, ...options });
    if (!response.ok) {
      const error = new Error(response.statusText);
      error.status = response.status;
      throw error;
    }
    return {
      key,
      data: await response.json(),
    };
  } catch (error) {
    error.key = key;
    throw error;
  }
};
 
export default httpClient;在Nuxt 3组件或页面中使用封装的HTTP客户端:
// some-component.vue
<script setup>
import httpClient from '~/path/to/http.js';
 
const fetchData = async () => {
  try {
    const { key, data } = await httpClient('https://api.example.com/data', {
      method: 'POST',
      body: JSON.stringify({ some: 'data' }),
    });
    console.log('Key:', key);
    console.log('Data:', data);
  } catch (error) {
    console.error('Error:', error);
  }
};
</script>在这个例子中,httpClient函数接受一个URL和一个选项对象,其中可以包含HTTP方法和请求体。它使用crypto模块的createHash方法来生成一个基于请求的URL、HTTP方法和请求体的哈希key。如果响应不是OK,它会抛出一个包含key的错误。在组件中,你可以调用httpClient来发送请求,并处理响应或错误。
评论已关闭