vue学习十八(axios)
Posted 易辰_
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了vue学习十八(axios)相关的知识,希望对你有一定的参考价值。
文章目录
安装
通过npm install axios
安装
或者直接用cdn <script src="https://unpkg.com/axios/dist/axios.min.js"></script>
get方法
我们来测试下get方法,这里我利用了cdn的方式
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<script src="https://cdn.jsdelivr.net/npm/vue@2.5.17/dist/vue.js"></script>
<script src="https://unpkg.com/vue-router@3.0.1/dist/vue-router.js"></script>
<script src="https://unpkg.com/vuex@2.0.0"></script>
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
</head>
<body>
</body>
<script>
axios.get('http://localhost:8080/pingg',
params:
name: "safly",
sex:"nan"
)
.then(function (response)
console.log(response.data);
)
.catch(function (error)
console.log(error);
)
.then(function ()
console.info("always executed")
);
</script>
</html>
浏览器输入file:///Users/zhiliao/zhiliao/vue/index_test.html
效果如下:
我们get请求,还可以用如下的方式来实现:
axios.get('http://localhost:8080/pingg?name=12345&sex=nan')
.then(function (response)
console.log(response.data);
)
.catch(function (error)
console.log(error);
)
.then(function ()
console.info("always executed")
);
/想要使用异步/等待?将“asycc”关键字添加到外部函数/方法中。
async function getUser()
try
const response = await axios.get('http://localhost:8080/pingg?name=12345&sex=nan');
console.log(response.data);
catch (error)
console.error(error);
getUser()
post方法
官网的例子是:
axios.post('/user',
firstName: 'Fred',
lastName: 'Flintstone'
)
.then(function (response)
console.log(response);
)
.catch(function (error)
console.log(error);
);
我用这个写法,我后端收不到,后来搜了网上,发现可以用如下解决方案:
var params = new URLSearchParams();
params.append('name', 'Fred');
params.append('sex', 'Flintstone');
axios.post('http://localhost:8080/pingp', params)
.then(function (response)
console.log(response.data);
)
.catch(function (error)
console.log(error);
);
批量请求
我们还可以同时发起多个请求
function getUserAccount()
return axios.get('http://localhost:8080/pingg?name=12345&sex=nan');
function getUserPermissions()
return axios.get('http://localhost:8080/pingg1?name=23423&sex=ssfsfs');
axios.all([getUserAccount(), getUserPermissions()])
.then(axios.spread(function (acct, perms)
console.info(acct.data,perms.data)
));
浏览器输入file:///Users/zhiliao/zhiliao/vue/index_test.html
效果如下:
后端代码
后端代码是利用go框架gin来构造的
package main
import (
"fmt"
"github.com/gin-gonic/gin"
"net/http"
"strings"
)
func main()
r := gin.Default()
r.Use(Cors())
r.GET("/pingg", func(c *gin.Context)
name := c.Query("name")
sex := c.Query("sex")
fmt.Println("pingg name>>>",name,"sex>>>",sex)
c.JSON(200, gin.H
"name": name,
"sex":sex,
)
)
r.GET("/pingg1", func(c *gin.Context)
name := c.Query("name")
sex := c.Query("sex")
fmt.Println("pingg1 name>>>",name,"sex>>>",sex)
c.JSON(200, gin.H
"name": name,
"sex":sex,
)
)
r.POST("/pingp", func(c *gin.Context)
name := c.PostForm("name")
sex := c.PostForm("sex")
fmt.Println("name>>>",name,"sex>>>",sex)
c.JSON(200, gin.H
"name": name,
"sex":sex,
)
)
r.Run()
func Cors() gin.HandlerFunc
return func(c *gin.Context)
method := c.Request.Method //请求方法
origin := c.Request.Header.Get("Origin") //请求头部
var headerKeys []string // 声明请求头keys
for k, _ := range c.Request.Header
headerKeys = append(headerKeys, k)
headerStr := strings.Join(headerKeys, ", ")
if headerStr != ""
headerStr = fmt.Sprintf("access-control-allow-origin, access-control-allow-headers, %s", headerStr)
else
headerStr = "access-control-allow-origin, access-control-allow-headers"
if origin != ""
c.Writer.Header().Set("Access-Control-Allow-Origin", "*")
c.Header("Access-Control-Allow-Origin", "*") // 这是允许访问所有域
c.Header("Access-Control-Allow-Methods", "POST, GET, OPTIONS, PUT, DELETE,UPDATE") //服务器支持的所有跨域请求的方法,为了避免浏览次请求的多次'预检'请求
// header的类型
c.Header("Access-Control-Allow-Headers", "Authorization, Content-Length, X-CSRF-Token, Token,session,X_Requested_With,Accept, Origin, Host, Connection, Accept-Encoding, Accept-Language,DNT, X-CustomHeader, Keep-Alive, User-Agent, X-Requested-With, If-Modified-Since, Cache-Control, Content-Type, Pragma")
// 允许跨域设置 可以返回其他子段
c.Header("Access-Control-Expose-Headers", "Content-Length, Access-Control-Allow-Origin, Access-Control-Allow-Headers,Cache-Control,Content-Language,Content-Type,Expires,Last-Modified,Pragma,FooBar") // 跨域关键设置 让浏览器可以解析
c.Header("Access-Control-Max-Age", "172800") // 缓存请求信息 单位为秒
c.Header("Access-Control-Allow-Credentials", "false") // 跨域请求是否需要带cookie信息 默认设置为true
c.Set("content-type", "application/json") // 设置返回格式是json
//放行所有OPTIONS方法
if method == "OPTIONS"
c.JSON(http.StatusOK, "Options Request!")
// 处理请求
c.Next() // 处理请求
以上是关于vue学习十八(axios)的主要内容,如果未能解决你的问题,请参考以下文章