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 querystringaxios({// 请求 postmethod:"post",//http://www.csdnts.com/login.jspx?userName=admin&passWord=123456url: "/login.jspx",//.stringifydata: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;})/** //简写getaxios.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;})//简写postaxios.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')
使用
//引用全局的简写getthis.$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;})//引用全局的简写postthis.$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;})