@胡海龙 2024-04-16 14:50 采纳率: 33.3%
浏览 10

Nuxt3 中使用 $fetch 内置函数请求获取不到header问题

Nuxt3 中使用 $fetch 内置函数请求获取不到header问题

目前我的前端使用Nuxt3进行开发,服务端使用SpringBoot3.2开发,目前遇到的问题是服务端给前端的Response中设置了一个token自定义头,但是通过$fetchonResponse 获取时发现headers为空。
目前服务端已经配置了跨域和相关头暴露的设置,代码如下:


package vip.huhailong.pengyouquan.config.intercepter;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.HttpHeaders;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

@Configuration
public class WebConfiguration implements WebMvcConfigurer {

  @Autowired
  StringRedisTemplate redisTemplate;

  @Override
  public void addInterceptors(InterceptorRegistry registry) {
    registry.addInterceptor(new AuthInterceptor(redisTemplate))
      .addPathPatterns("/**")
      .excludePathPatterns("/auth/**");
  }

  @Override
  public void addCorsMappings(CorsRegistry registry) {
    registry.addMapping("/**")
      .allowedOrigins("*")
      .allowedMethods("GET", "POST", "DELETE", "PUT")
      .allowedHeaders("*")
      .exposedHeaders("token");
  }
}

目前跨域配置没有问题,然后使用 exposeheaders 暴露出了 token 自定义头。
在使用浏览器请求时,响应标头可以看到token值,但是$fetch无法获取,前端代码如下:

    const response = await $fetch.raw('/auth/login', {
        method: 'post',
        baseURL: config.public.apiURL,
        headers: {
            'Content-Type': 'application/json',
        },
        body: {
            email: email.value,
            verificationCode: verificationCode.value
        }
    })
    console.log(response)

控制台发现对应的headers为空。
但是我使用axios框架请求时是可以获取到headers的,刚开始使用nuxt$fetch这种方式,有点搞不懂了,我该怎么做才能获取到头呢?

  • 写回答

3条回答 默认 最新

  • 专家-赤兔[在线] 全栈领域优质创作者 2024-04-16 14:50
    关注

    引自免费微信小程序:皆我百晓生

    看起来你的 Nuxt.js 应用程序配置得基本正确,但可能是因为 $fetchraw 方法不会自动处理响应头。要解决这个问题,你可以尝试使用标准的 fetch API 而不是 $fetch.raw。这样,你可以直接操作返回的 Promise,并从 Response 对象中提取你需要的 header。

    首先,在你的组件中取消导入 $fetch,然后使用标准的 fetch 函数。下面是一个例子:

    <script>
    export default {
      async fetch({ error }) {
        try {
          const response = await fetch(`${config.public.apiURL}/auth/login`, {
            method: 'POST',
            headers: {
              'Content-Type': 'application/json',
            },
            body: JSON.stringify({
              email: this.email,
              verificationCode: this.verificationCode,
            }),
          });
    
          if (!response.ok) {
            throw new Error('Error occurred while fetching data');
          }
    
          // 如果需要解析响应体为JSON
          const json = await response.json();
    
          // 访问头部信息
          const token = response.headers.get('token');
    
          // 在这里可以对数据进行处理并存储 token
          console.log(token);
          console.log(json);
    
        } catch (error) {
          error.message && error.status && error.response
            ? error.response.json().then(errorData => error.error = errorData)
            : null;
          error.statusCode = 500;
          error.message = error.message || 'An error occurred';
          error.isSoftError = true;
          error.stack = '';
          error.statusCode = 500;
          error.meta = { type: 'api' };
          error.error = error.message;
          error.description = error.message;
          error.isApiError = true;
          error.isServerError = true;
          error.requestId = Math.random().toString(36).substring(7);
          error.timestamp = Date.now();
          error.method = 'POST';
          error.url = `/auth/login`;
          error.type = 'internal_server_error';
    
          return Promise.reject(error);
        }
      },
    };
    </script>
    
    <style scoped></style>
    

    在这个例子中,我们使用了标准的 fetch 函数来发起请求,并且处理了响应的状态码和错误情况。接着,我们可以直接从 response.headers.get('token') 获取到 token 头部。

    确保你在 Nuxt.js 应用中启用了 CORS。如果你之前已经在服务端配置了 CORS,那么这一步应该不需要额外操作。不过,为了保险起见,可以在 Nuxt 配置文件(nuxt.config.js)中添加以下内容:

    module.exports = {
      ...
      server: {
        cors: {
          origin: '*',
          methods: ['GET', 'POST', 'DELETE', 'PUT'],
          allowedHeaders: ['*'],
          exposedHeaders: ['token'],
        },
      },
      ...
    };
    

    这样应该能让你在 Nuxt.js 中通过 fetch 函数正常地获取到自定义的 token 头部。如果仍然有问题,建议检查一下网络请求是否正确发出,以及服务器返回的响应头是否确实包含 token。你可以在浏览器开发者工具的 Network 面板中查看这些信息。

    评论 编辑记录

报告相同问题?

问题事件

  • 创建了问题 4月16日

悬赏问题

  • ¥15 c语言怎么用printf(“\b \b”)与getch()实现黑框里写入与删除?
  • ¥20 怎么用dlib库的算法识别小麦病虫害
  • ¥15 华为ensp模拟器中S5700交换机在配置过程中老是反复重启
  • ¥15 java写代码遇到问题,求帮助
  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?