Vue3 Axios网络请求简单应用

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

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

运行示例:

Vue3 Axios网络请求简单应用_第1张图片

后台接口: 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 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 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







文件:vue.config.js 

Vue3 Axios网络请求简单应用_第2张图片

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;
    })

你可能感兴趣的:(Vue相关,前端,vue,java,网络)