Vue3 Axios网络请求简单应用

cd 到项目 安装Axios:cnpm install --save axios

post传递参数 需要安装querystring 用于转换参数格式cnpm install --save querystring

运行示例:

后台接口: GetTestData.java

package com.csdnts.api;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;

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 com.csdnts.dto.User;    
import com.google.gson.Gson;

/**
 * Servlet implementation class GetTest
 */
@WebServlet("/getTestData.jspx")
public class GetTestData extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public GetTestData() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO doGet() 后台解决跨越问题
		
		//数据
		List<User> users = new ArrayList<>();
		User user = new User();
		user.setName("张三丰");
		user.setAge(25);
		user.setSex("男");
		
		User user2 = new User();
		user2.setName("周芷若");
		user2.setAge(22);
		user2.setSex("女");
		
		users.add(user);
		users.add(user2);
		
		Gson gson = new Gson();
		
		//[{"name":"张三丰","sex":"男","age":25},{"name":"周芷若","sex":"女","age":22}]
		String userString = gson.toJson(users);
		
		/**设置响应头 解决跨越问题
		 * 这样,你的Servlet将允许来自任何域名的跨域请求,并且能够正常返回数据。
		 * 请注意,CORS是一种安全机制,它在浏览器中执行。因此,即使你在后台配置了CORS头信息,
		 * 浏览器仍然会根据这些头信息来判断是否允许跨域请求。
		 * 如果浏览器不支持CORS或者请求中包含不允许的头信息,仍然会被浏览器拦截。
		 * 你可以根据需要修改Access-Control-Allow-Origin头信息的值来指定允许访问的域名,
		 * 如果你希望允许来自任何域名的访问,可以将其设置为"*"。
		 * */
		response.setHeader("Access-Control-Allow-Origin", "*");
		response.setHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE");
		response.setHeader("Access-Control-Allow-Headers", "Content-Type");
		response.setHeader("Access-Control-Max-Age", "3600");
		//输出到页面
		response.setContentType("text/html");
		response.setCharacterEncoding("UTF-8");
		PrintWriter out = response.getWriter();
		out.print(userString);
		out.flush();
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO doPost 后台没有解决跨越问题
		
		//数据
		List<User> users = new ArrayList<>();
		User user = new User();
		user.setName("张三");
		user.setAge(25);
		user.setSex("男");
		
		User user2 = new User();
		user2.setName("李四");
		user2.setAge(22);
		user2.setSex("女");
		
		users.add(user);
		users.add(user2);
		
		Gson gson = new Gson();
		
		//[{"name":"张三","sex":"男","age":25},{"name":"李四","sex":"女","age":22}]
		String userString = gson.toJson(users);
		
		//输出到页面
		response.setContentType("text/html");
		response.setCharacterEncoding("UTF-8");
		PrintWriter out = response.getWriter();
		out.print(userString);
		out.flush();
	}

}

后台接口: Login.java

package com.csdnts.api;

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

/**
 * Servlet implementation class Login
 */
@WebServlet("/login.jspx")
public class Login extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public Login() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO 参数传递  在后台没有解决跨越问题,在前台处理了

		//获取参数
		String userName = request.getParameter("userName");
		String passWord = request.getParameter("passWord");

		System.out.println("userName:"+userName);
		System.out.println("passWord:"+passWord);
		
		if(userName != null && !"".equals(userName) && passWord != null && !"".equals(passWord)){
			//有数据
			if(userName.equals("admin") && passWord.equals("123456")){
				//用户名密码正确
				//输出到页面
				outPrint(response,"恭喜"+userName+"登录成功");
			}else{
				//用户名密码正确错误
				outPrint(response,"用户名或密码错误");
			}
			
		}else{
			//空
			outPrint(response,"用户名或密码为空");
		}
		
	}

	private void outPrint(HttpServletResponse response, String msg) throws IOException {
		// TODO 把结果输出到页面
		response.setContentType("text/html");
		response.setCharacterEncoding("UTF-8");
		PrintWriter out = response.getWriter();
		out.print(msg);
		out.flush();
	}

}

前台代码: HelloWorld.vue

<template>
  <div class="hello">
    <h2>Vue Axios网络请求</h2>
    <h3>从网络上获取到的数据get:{{ getmsg }}</h3>
    <h3>从网络上获取到的数据post:{{ postmsg }}</h3>
    <h3>登录状态:{{ loginMsg }}</h3>
  </div>
</template>

<script>
 import axios from "axios"
 import querystring from "querystring"

export default {
  name: 'HelloWorld',
  data(){
    return{
      getmsg:"",
      postmsg:"",
      loginMsg:""
    }
  },
  // 组件生命周期方法 组件渲染完成执行此方法
  mounted(){
    axios({
      //get 请求 
      method:"get",
      //    http://www.csdnts.com 你的域名  这个是假的
      url: "http://www.csdnts.com/getTestData.jspx"   //get
     // 成功
    }).then(res =>{
      console.log(res);
      console.log(res.data);
     this.getmsg = res.data;
     // 失败
    }).catch(err =>{
      console.log(err);
      this.getmsg =err;
    })

    axios({
      // post请求 由于post请求后台没有解决跨越问题 会发生报错。AxiosError: Network Error
      // 也可以在前台 解决跨越问题 打开vue.config.js 文件 设置proxy  重启服务再次运行就可以了
      method:"post",
      url: "/getTestData.jspx"                                //post
     // 成功
    }).then(res =>{
      console.log(res);
      console.log(res.data);
     this.postmsg = res.data;
     // 失败
    }).catch(err =>{
      console.log(err);
      this.postmsg =err;
    })

  //post 传递参数 需要安装 queryString 转换参数格式   cnpm install --save querystring
    axios({
      // 请求 post
      method:"post",
      //http://www.csdnts.com/login.jspx?userName=admin&passWord=123456
      url: "/login.jspx",
      //.stringify
      data:querystring.stringify({
        userName:"admin",
        passWord:"123456"
      })
     // 成功
    }).then(res =>{
      console.log(res);
      console.log(res.data);
     this.loginMsg = res.data;
     // 失败
    }).catch(err =>{
      console.log(err);
      this.loginMsg =err;
    })

/** 
    //简写get
    axios.get("http://www.csdnts.com/getTestData.jspx")
    .then(res =>{
      console.log(res.data);
     this.getmsg = res.data;
    }).catch(err =>{
      console.log(err);
      this.getmsg =err;
    })

     //简写post
     axios.post("/login.jspx",querystring.stringify({
        userName:"admin",
        passWord:"123456"
      }))
      .then(res =>{
      console.log(res.data);
     this.loginMsg = res.data;
    }).catch(err =>{
      console.log(err);
      this.loginMsg =err;
    })
 */

  }
}
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
h3 {
  margin: 40px 0 0;
}
ul {
  list-style-type: none;
  padding: 0;
}
li {
  display: inline-block;
  margin: 0 10px;
}
a {
  color: #42b983;
}
</style>

文件:vue.config.js 

vue.config.js 

const { defineConfig } = require('@vue/cli-service')
module.exports = defineConfig({
  transpileDependencies: true,
  devServer:{
    proxy:{
      '/api':{
        target:'http://www.csdnts.com', //你的域名 演示用这个是假的
        changeOrigin:true
      }
    }
  }

})

扩展 :全局引用Axios

main.js

import { createApp } from 'vue'
import App from './App.vue'
import './registerServiceWorker'
//引入axios
import axios from 'axios'

// 把Axios 挂载到全局  起的名字 $axios,引用 this.$axios.get()  this.$axios.post()
const app = createApp(App)
app.config.globalProperties.$axios = axios
app.mount('#app')

使用

//引用全局的简写get
    this.$axios.get("http://www.csdnts.com/getTestData.jspx")
    .then(res =>{
      console.log(res.data);
     this.getmsg = res.data;
    }).catch(err =>{
      console.log(err);
      this.getmsg =err;
    })

     //引用全局的简写post
     this.$axios.post("/api/login.jspx",querystring.stringify({
        userName:"admin",
        passWord:"123456"
      }))
      .then(res =>{
      console.log(res.data);
     this.loginMsg = res.data;
    }).catch(err =>{
      console.log(err);
      this.loginMsg =err;
    })

没有设置跨域报错:

has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

javaGHui

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值