(十二)axios實現前后端交互(post,get請求傳參,URLSearchParams傳參)


使用axios實現前后端交互:

1:安裝axios模塊,后面加上--save方便移動項目的時候也能使用模塊

npm install axios --save

2:html代碼定義按鈕

  <button @click="getData()">axios的post獲取數據</button>
  <button @click="getDataGet()">axios的get獲取數據</button>
  <br/><br/><br/>
  <ul>
    <li v-for="(item,index) in list" :key="index">
      {{item.name}}--{{item.no}}
    </li>
  </ul>
3js業務邏輯
<script>
//  import axios from "axios";//這個可以注冊到vue的全局變量里面方便在任意地方取值
//<script>定業務邏輯得
export default {
  name: "App",
  data() {
    //把業務邏輯得數據渲染到頁面上
    return {
     list: [],
    };
  },
  components: {
  },
methods: {
    getData() {
      var api = "http://localhost:43597/api/Test/Getvalue";
      var param=new URLSearchParams();//URLSearchParams方式動態拼接參數
      param.append('id','111');
      param.append('name','2222');
      this.$Http
         //.post(api,{id:'111',name:'222'})//后台只能以一個對象的方式接收,如果后台是屬性一一對應接收,接收到的會是null
         //.post(api,{},{params:{id:'111',name:'222'}})//后台只能是屬性一一對應接收,如果接收的是一個對象,接收到的將會是null,下面是動態拼參的結果
          .post(api,{},{params:param})
        .then((response) => {
          alert(response.data);
        })
        .catch((err) => {
          alert(err);
        });
    },
    getDataGet() {
      // var api = "http://localhost:43597/api/Test/ToJson?id1=n111&name1=n222";//直接問好后面拼接
      var api = "http://localhost:43597/api/Test/ToJson";
      var param=new URLSearchParams();//通過URLSearchParams動態拼參
      param.append('id1','111');
      param.append('name1','666');
      this.$Http
        .get(api,
          // {params:{id1:"n131",name1:"n333"}}//等同於上面的?id1=n111&name1=n222
          {params:param}//動態拼參的結果
        )
        .then((response) => {
          this.list = response.data;
        })
        .catch((err) => {
          alert(err);
        });
    },
},
  
  
};
</script>
4:在main.js里面注冊全局變量$Http ,后面在任意地方都可以通過this.$Http來取Axios對象
import Axios from "axios";
const app=createApp(App);
app.config.globalProperties.$Http=Axios ;//注冊全局變量$Http
//掛載路由
app.use(router)
app.mount('#app1')
 
后端代碼:

1:ConfigureServices里面配置跨域

string corsUrls = "http://192.168.2.117:8081,http://192.168.2.117:8080,http://192.168.2.117:8082,http://192.168.2.117:8083";
if (string.IsNullOrEmpty(corsUrls))
{
throw new Exception("請配置跨請求的前端Url");
}
services.AddCors(options =>
{
options.AddDefaultPolicy(
builder =>
{
builder.WithOrigins(corsUrls.Split(",")).AllowCredentials()
.AllowAnyHeader().AllowAnyMethod();
});
});

2:Configure里面啟用跨域

app.UseCors();//啟用跨域,啟用跨域寫在UseAuthorization上面
app.UseAuthorization();

 
3.后端的controller的代碼放字符串或者json

[Route("/api/Test")]
[ApiController]
public class TestController : ControllerBase
{

[Route("Getvalue")]
[HttpPost]
//public string Getvalue(Querys querys
public string Getvalue(string id, string name)
{

return "1111";
}

[Route("ToJson")]
[HttpGet]
public string ToJson(string id1, string name1)
{
List<people> peoples = new List<people>() {
new people() { name="zhangsan",no="111"} ,
new people() { name="李四",no = "222" }
};
string ListJson = JsonConvert.SerializeObject(peoples);
return ListJson;
}


}
public class people
{
public string name { get; set; }
public string no { get; set; }
}
public class Querys{
public string id { get; set; }
public string name { get; set; }
}

 

注意點:post后台和前台屬性命名一一對應獲取,不用對象獲取的時候,參的參數應該放在第3個,也就是api路徑后面必須加{},然后在是傳的參數,不然后台獲取為null

.post(api,{},{params:{id:'111',name:'222'}})//傳值方式

 public string Getvalue(string id, string name)//獲取方式


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM