vue使用axios请求后端数据

前后端分离项目的基础:

前后端跨域访问

vite.config.js中加入

复制代码
  // 1.为什么要跨域
//因为浏览器的同源策略,不同站点之间访问需要跨域
//实现跨域的方式:
  server: {
    proxy: {
      // 假设要跨域访问的后端 API 地址以 /api 开头
      '/api': { //表示拦截以/api开头的请求路径
        target: 'http://localhost:8089/', // 后端服务的实际地址
        changeOrigin: true,           //是否开启跨域
        rewrite: (path) => path.replace(/^\/api/, ''),//把/api变成空字符串
      },
    },
  },

完整vite.config.js文件

复制代码
import { fileURLToPath, URL } from 'node:url'

import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'

// https://vitejs.dev/config/
export default defineConfig({
  plugins: [
    vue(),
  ],
  resolve: {
    alias: {
      '@': fileURLToPath(new URL('./src', import.meta.url))
    }
  },
  // 1.为什么要跨域
//因为浏览器的同源策略,不同站点之间访问需要跨域
//实现跨域的方式:
  server: {
    proxy: {
      // 假设要跨域访问的后端 API 地址以 /api 开头
      '/api': { //表示拦截以/api开头的请求路径
        target: 'http://localhost:8089/', // 后端服务的实际地址
        changeOrigin: true,           //是否开启跨域
        rewrite: (path) => path.replace(/^\/api/, ''),//把/api变成空字符串
      },
    },
  },
})

App.vue文件

复制代码
<template>
    <button @click="handleClick">跨域请求</button>
</template>

<script setup>
import axios from 'axios'; // 正确从 'axios' 包导入 axios  
       //将axios请求写在方法里面,通过点击事件调用方法向后端拿数据
       function  handleClick(){
           axios.get("api/Axios").then(Response=>{
               console.log(Response.data);
           })
           .catch(error=>{
               console.log('Error fetching data:',error);
           },
           )
         }
</script>

<style scoped>

</style>

Java中的servlet 服务

需要在maven的pom.xml中导入fastjson

复制代码
  <dependency>
      <groupId>com.alibaba</groupId>
      <artifactId>fastjson</artifactId>
      <version>1.2.76</version>
    </dependency>

package Study.day08;

import com.alibaba.fastjson.JSON;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet("/Axios")
public class Axios extends HttpServlet{
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        Student student=new Student("张三","男",23);
        req.setCharacterEncoding("utf-8");
        resp.setContentType("text/json; charset=utf-8");
        resp.getWriter().println(JSON.toJSON(student));
    }
}

后端服务访问页面:

前端成功拿到后端数据:

相关推荐
fthux19 分钟前
RenoPit 能为普通业主做什么?看懂图纸、审查合同,提前发现装修坑
javascript·人工智能·ai·开源·github·chrome扩展·open source·edge扩展·firefox扩展
仿生狮子1 小时前
✂️ Nuxt 最简单的字体裁剪工具:Fontize
javascript·vue.js·nuxt.js
IKUN家族3 小时前
Spring MVC(一)
java·spring·mvc
石小石Orz4 小时前
我发现了开发者AI产品营收的新方向
前端·虚拟现实
老马识途2.04 小时前
关于跨域问题的总结
java·前端
魔力女仆5 小时前
分享一个 JS 鼠标跟随贪吃蛇背景库
开发语言·javascript·计算机外设
都叫我大帅哥5 小时前
Java日期时间三十年战争:从Date考古到LocalDateTime革命,以及数据库与前端的那点事儿
java
Muscleheng5 小时前
SpringBoot 集成 DeepSeek 实现 RAG 文档问答
java·spring boot·ai·springai
2501_936415696 小时前
可变参数&综合练习&斗地主游戏
java·windows·游戏
别惊醒渔人6 小时前
Vue3 Diff 优化:最长递增子序列 LIS
前端·javascript·vue.js