VSCode+Vue+Axios编写HelloWorld项目源码
VSCode+Vue+Axios编写HelloWorld项目源码
目录
一、前端源码修改
main.js
JavaScript 全选
// The Vue build version to load with the `import` command
// (runtime-only or standalone) has been set in webpack.base.conf with an alias.
import Vue from 'vue'
import App from './App'
import axios from 'axios'
import Routers from './router'
import VueRouter from 'vue-router'
Vue.use(VueRouter)
Vue.config.productionTip = false
Vue.prototype.axios = axios
/* eslint-disable no-new */
new Vue({
el: '#app',
router: Routers,
components: {
App
},
template: '<App/>'
})
App.vue
HTML 全选
<template>
<div id="app">
<h1>{{msg}}</h1>
<div id="test">
<span>通过Axios调用Api接口返回数据:</span>
<div>
Code: {{code}}<br>
Name: {{name}}
</div>
</div>
</div>
</template>
<script>
/* eslint-disable */
export default {
name: "hello",
data() {
return {
code: "",
name: "",
msg: "HELLO WORLD!,this is my first project!",
};
},
created() {
this.loadData();
},
mounted() {},
beforeDestroy() {},
methods: {
loadData() {
var _T = this;
this.axios
.post("/api/get.aspx")
.then(function (res) {
_T.code = res.data.code;
_T.name = res.data.name;
})
.catch(function (res) {
console.log(res);
});
},
},
};
</script>
<style>
#app {
font-family: "Avenir", Helvetica, Arial, sans-serif;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
text-align: center;
color: #2c3e50;
margin-top: 60px;
}
</style>
二、CORS跨域问题导致无法访问API
原因分析
本测试案例调用服务端Api接口,因开发环境的http地址与服务器IP地址、端口不同,导致CORS跨域访问:
后端服务:http://localhost:4618/api/get.aspx
CORS error 跨域访问Api接口失败
解决方案:添加 proxyTable
在index.js添加源码
JavaScript 全选
}module.exports = {
dev: {
// Paths
assetsSubDirectory: 'static',
assetsPublicPath: '/',
proxyTable: {
'/api': {
target: 'http://localhost:4618', //请求域名
//secure: false, // 如果是https接口,需要配置这个参数
changeOrigin: true, //如果是跨域访问,需要配置这个参数
pathRewrite: {
'^/api': ''
}
}
}
}
使用Axios访问Api接口,给前端页面赋值
JavaScript 全选
<script>
/* eslint-disable */
export default {
name: "hello",
data() {
return {
code: "",
name: "",
msg: "HELLO WORLD!,this is my first project!",
};
},
created() {
this.loadData();
},
mounted() {},
beforeDestroy() {},
methods: {
loadData() {
var _T = this;
this.axios
.post("/api/get.aspx")
.then(function (res) {
_T.code = res.data.code;
_T.name = res.data.name;
})
.catch(function (res) {
console.log(res);
});
},
},
};
</script>
三、服务端 ASP.NET
cscode_get.aspx
C# 全选
public partial class cscode_get : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (this.IsPostBack) return;
if (this.Request.RequestType == "POST")
{
try
{
MyPerson p = new MyPerson
{
code = "C000001",
name = "VUE",
};
var json = JsonConvert.SerializeObject(p);
this.Response.ContentType = "application/json";
this.Response.Write(json);
}
catch (Exception ex)
{
this.DoResponse("PageLoad:内部异常!");
}
}
}
}
MyPerson模型
C# 全选
public class MyPerson
{
public string code { get; set; }
public string name { get; set; }
}
四、运行前端测试
打开命令行,输入:
npm run dev
版权声明:本文为开发框架文库发布内容,转载请附上原文出处连接
YESWEB C/S框架网