API: 都是学习的成果 - Gitee.com GIT仓库可以提取源码(包含接口和这次的)
上次写了jwt验证的接口,这次前端写个调用接口试试
(54条消息) 【无标题】_m0_59504468的博客-CSDN博客
首先先试试这三个接口有问题没,用工具postman试试
可以看见都没有问题都是可以访问到的
接下来直接上前端
代码
<!-- <!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
</body>
</html> -->
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<!-- <script src="https://cdn.jsdelivr.net/npm/vue"></script> -->
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/vue@2/dist/vue.js"></script>
<script src="https://cdn.bootcdn.net/ajax/libs/qs/6.11.0/qs.min.js"></script>
<body>
<div id="app">
<input type="text" v-model="name " placeholder="请输入用户名"></br>
<input type="text" v-model="realname " placeholder="请输入真实姓名"></br>
<button @click="testGet">登录</button></br>
<button @click="testlist">token验证</button></br>
<button @click="testuser">解析token获取用户名</button>
</div>
</body>
<script>
const vm = new Vue({
el: '#app',
data: {
name: '',
realname: '',
// tokentype:token_type,
// tokenbear:token
token: ''
},
methods: {
testGet() {
axios
.get('http://localhost:5001/api/test/getlogin', {
params: {
name: this.name,
realname: this.realname
}
})
.then(response => {
console.log(response);
this.token = response.data.access_token
console.log(this.token);
alert("登录成功了token获取到了")
// console.log(token)
// this.testGetData = response.data.return_data[0].content
})
.catch(function (error) { // 请求失败处理
console.log(error);
});
},
testlist() {
//验证
axios
.get('http://localhost:5001/api/test/GetDataList', {
// Headers.Authorization:{}
// Headers:{
// "Authorization" :this.token,
// },
// Authorization: this.token,
params: {
},
headers: {
'Authorization':'Bearer ' + this.token //这里是关键,设置好Authorization,将定义的token放在后面即可
}
})
.then(response => {
console.log(response);
})
.catch(function (error) { // 请求失败处理
console.log(error);
});
},
//解析token并获取用户名和角色信息
testuser(){
axios
.get('http://localhost:5001/api/test/Getuser', {
// Headers.Authorization:{}
// Headers:{
// "Authorization" :this.token,
// },
// Authorization: this.token,
params: {
},
headers: {
'Authorization':'Bearer ' + this.token //这里是关键,设置好Authorization,将定义的token放在后面即可
}
})
.then(response => {
console.log(response);
})
.catch(function (error) { // 请求失败处理
console.log(error);
});
}
},
mounted() {
}
})
</script>
</html>
第一个接口调用
可以看到ok可以访问到,也有数据
点击第二个按钮token验证也可以访问到
第三个,都是没有问题的
不过其中还涉及了一个知识点跨域问题
Microsoft.AspNet.WebApi.Cors下载这个包,然后配置服务
这样就OK了,不然的话你再调用的话就会报错,可能会是这样的错误
翻译的话就是这样
具体问题需要自己去了解,按照我上面的操作就可以把问题解决
本文含有隐藏内容,请 开通VIP 后查看