nuxt项目中使用axios

本文详细介绍了在Nuxt项目中集成Axios模块的步骤,包括使用yarn或npm安装@nuxtjs/axios,配置nuxt.config.js以实现请求前缀和代理设置,以及在页面中使用$axios进行HTTP请求的示例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

项目环境:nuxt+vue+axios

针对问题:如何在vue框架nuxt中使用axios模块

解决思路:

                   (1) 把nuxtjs-axios模块添加项目中

                   (2) 配置nuxt.config.js

                   (3) 简单使用

参考网址:http://www.axios-js.com/zh-cn/docs/nuxtjs-axios.html

注意事项:前台框架不同,使用的模块也有些不一样的。

                  例如:你没有使用nuxt框架,只使用vue,那么添加axios模块方式是:npm install --save axios vue-axios

具体步骤:

1. 把nuxtjs-axios模块添加到项目

     yarn add @nuxtjs/axios       // 使用yarn来安装模块

     npm install @nuxtjs/axios  // 使用npm来安装模块

注:不同的包管理器,要使用不同的命令

2. 配置nuxt.config.js

    简单使用 

  modules: [
    '@nuxtjs/axios'
  ],
 

    如果这步完成,可以在项目中方法使用console.log(this)  ,这时候可以看到该对象中有$axios属性了

    如果你想使用代理可以这样写

  modules: [
    '@nuxtjs/axios'
  ],
  axios: {
    prefix: '/app',  //在请求路径前,加上 /app
    proxy: true
  },
  proxy: {
    '/app': { 
        target: 'http://127.0.0.1:8080', //页面仍然显示 http://localhost:3000,但实际上是
                                        //http://127.0.0.1:8080
        pathRewrite: {'^/app': '/test'}    //前面是一个正则表达式,后面是替换后的内容
                              
     }
  },

 当我们使用axios发送请求时
 如果你使用axios发送请求且路径是/helo/hello, 
 那么会被axios中的prefix属性加上前缀,即/app/helo/helo
 而proxy会使得请求变为,http://127.0.0.1:8080/app/helo/helo 
 而pathRewrite会把请求变为 http://127.0.0.1:8080/test/helo/helo

 

3.例子:

(1)页面中发送的请求时  /helo/helo

<template>
  <div class="container">
    <div @click="loadData">
        显示 
    </div>
  </div>
</template>

<script>
export default {
  methods:{
    loadData(){
      this.$axios.get("/helo/helo?message='hello world'").then(({data})=>{
        console.log(data)
      })
    
    }
  } 
}
 </script>

(2)页面发送的请求 是/helo/helo ,实际上请求是http://localhost:8080/test/helo/helo,但页面只能看到的是

         http://localhost:3000/app/helo/helo,

module.exports = {
  mode: 'universal',
  head: {
    title: process.env.npm_package_name || '',
    meta: [
      { charset: 'utf-8' },
      { name: 'viewport', content: 'width=device-width, initial-scale=1' },
      { hid: 'description', name: 'description', content: process.env.npm_package_description || '' }
    ],
    link: [
      { rel: 'icon', type: 'image/x-icon', href: '/favicon.ico' }
    ]
  },
  loading: { color: '#fff' },
  css: [
  ],
  plugins: [
  ],
  modules: [
    '@nuxtjs/axios',
  ],
  axios: {
    prefix: '/app',  //在请求路径前,加上 /app
    proxy: true
  },
  proxy: {
    '/app': { 
        target: 'http://127.0.0.1:8080',   //页面仍然显示 http://localhost:3000,但实际上是
                                           //http://127.0.0.1:8080
        pathRewrite: {'^/app': '/test'}    //前面是一个正则表达式,后面是替换后的内容
     }
  },
  build: {
    extend(config, ctx) {
    }
  }
}

 

(3) showMsg方法能够处理的请求是,http://localhost:8080/test/helo/helo

package com.example.demo.controller;

import java.util.HashMap;
import java.util.Map;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
@RequestMapping("/test/helo")
public class HeloController {
	@RequestMapping("/helo")
	@ResponseBody
	public String showMsg(String message) {
		return message;
	}
}

 

Nuxt 3 中集成 Axios 可以通过官方提供的模块 `@nuxtjs/axios` 或直接使用原生配置来完成。以下是详细的步骤以及一些注意事项: ### 步骤一:安装依赖 首先需要确保项目中有 Axios 的支持。虽然 Nuxt 社区推荐的 `@nuxtjs/axios` 模块尚未完全适配 Nuxt 3,但仍可以手动设置 Axios。 运行以下命令添加 Axios 到您的项目: ```bash npm install axios ``` ### 步骤二:创建插件文件 接下来,在项目的 `plugins` 文件夹下新建一个名为 `axios.js` 的插件文件,并注册它到应用中。 #### 插件内容示例 (`plugins/axios.js`): ```javascript import { defineNuxtPlugin } from '#app' import axios from 'axios' export default defineNuxtPlugin((nuxtApp) => { const apiClient = axios.create({ baseURL: 'https://api.example.com', // 设置基础URL withCredentials: false, headers: { common: { 'Authorization': 'Bearer your_token_here', } }, }) nuxtApp.provide('axios', apiClient) }) ``` 上述代码将自定义化的 Axios 客户端实例注入了 Vue 应用上下文中,你可以通过 `this.$axios` (组件内部) 来访问它。 ### 步骤三:启用插件 在 `nuxt.config.ts` 配置文件内声明此插件生效。 ```typescript export default defineNuxtConfig({ plugins: [ '~/plugins/axios.js' ] }) ``` ### 使用方法 现在可以在页面、组件甚至组合式 API 中轻松获取并利用 Axios 实现网络请求功能。 例如在一个 `.vue` 组件里调用 GET 请求: ```html <script setup> const runtimeConfig = useRuntimeConfig() const { data, error } = await $fetch('/endpoint', { method:'GET', }) if(error.value){ console.error("发生错误",error.value); } </script> <template> <div>{{data}}</div> </template> ``` 注意这里我们还借助 `$fetch`, 这是由 Nuxt 内建封装过的轻量级 fetch 工具。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值