【Vue】通过axios实现跨域与asp.net后台数据get/post传递(图文+代码示例)

说明:如果是vue脚手架,发布后的静态项目,直接联后台的asp.net中的webAPI项目,直接改web.config文件。

    <httpProtocol>
      <customHeaders>
        <add name="Access-Control-Allow-Methods" value="GET,POST,PUT,DELETE,OPTIONS" />
        <add name="Access-Control-Allow-Headers" value="*" />
        <add name="Access-Control-Allow-Origin" value="*" />
      </customHeaders>
    </httpProtocol>

 

一、不跨域的解决方案

注意前提:需要在同一个C#项目(asp.net)中,否则会出现跨域问题。

Home.html代码

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title></title>
    <script src="Content/vue.js"></script>
    <script src="https://cdn.staticfile.org/axios/0.18.0/axios.min.js"></script>
</head>

<body>
    <div id="box">

        ---- Vue数据列表 ---- <br>
        <ul>
            <li v-for="p in persons" :key="p.id">
                {{p.id}} {{p.name}}-{{p.age}}岁
                <button @click="submit(p.id)">提交后台获取ID值</button>
            </li>

        </ul>

    </div>
    <script type="text/javascript">
        var box = new Vue({
            el: "#box",
            data: {
                persons: [
                    {
                        id: "1",
                        name: "张飞",
                        age: 20
                    },
                    {
                        id: "2",
                        name: "刘备",
                        age: 30
                    },
                    {
                        id: "3",
                        name: "吕布",
                        age: 22
                    }
                ]
            },
            mounted() {
                axios
                    .get('/Home/ListJson')
                    .then(response => (this.persons = response.data))
                    .catch(function (error) { // 请求失败处理
                        console.log(error);
                    });
            },
            methods: {
                submit(a) {
                    alert("把当前记录ID:[" + a + "]提交给后台.");
                    axios
                        .post('/Home/SubmitJson', {
                            paramA: a
                        })
                        .then(response => (alert(response.data)))
                        .catch(function (error) { // 请求失败处理
                            console.log(error);
                        });
                }
            }

        })
    </script>

</body>

</html>

二、axios跨域与asp.net的解决方案

1、 axios的安装与环境配置,请参考下面的链接

【Vue】通过脚手架配置代理实现axios跨域与第三方后台数据传递(图文+代码示例)_敦厚的曹操的博客-CSDN博客一、脚手架环境安装xios命令:npm i axios二、在组件中引入axiosimport axios from 'axios'三、设置代理服务器打开vue.config.js文件,添加以下代码(注意:端口号是第三方的端口号):方式一:单个端口(不推荐使用) // 开启代理服务器 devServer: { proxy: 'http://localhost:22911' }方式二:多个端口(推荐使用)vue.config.js..https://blog.csdn.net/dxnn520/article/details/124630432

2、Vue前台页面,login.vue

<template>
  <div>
    <el-form ref="form" :model="loginForm">
      <h3>系统登录</h3>
      <el-form-item>
        <el-input
          type="text"
          autocomplete="off"
          v-model="loginForm.username"
          placeholder="请输入用户名"
        ></el-input>
      </el-form-item>
      <el-form-item>
        <el-input
          type="password"
          auto-complete="false"
          v-model="loginForm.password"
          placeholder="请输入密码"
        ></el-input>
      </el-form-item>
      <el-button
        @click="loginClick"
        type="primary"
        size="medium"
        style="width: 100%"
        >登 录
      </el-button>
    </el-form>
  </div>
</template>
<script>
import axios from "axios";
export default {
  data() {
    return {
      loginForm: {
        username: "",
        password: "",
      },
    };
  },
  methods: {
    loginClick() {
      axios
        .post("http://localhost:8080/3954/handle/login.ashx?id=888", {
          username: this.loginForm.username,
          password: this.loginForm.password,
          message: "终于解决了!",
        })
        .then((response) => {
          alert(response.data);
          console.log(response.data);
        })
        .catch(function (error) {
          console.log(error);
        });
    },
  },
};
</script>
<style scoped>
</style>

3、Asp.net代码,login.aspx \ login.aspx.cs \ login.ashx \ login.cs

注意:axios中的传参跟ajax不同,asp.net后台接收到的是JSON格式,不是字符串格式,需要转换成字符串格式

在此感谢:herryDong博主给的分享

解决ASP.NET中ashx文件无法接收前端axios传递的数据的方法_HerryDong的博客-CSDN博客踩了一个早上的坑,算是搞定axios的传值问题了。假设我们现在需要传递一个数值到后台,后台可以计算该数的平方,最后把计算后的平方值返回前端界面。对于该问题,我们先来看一下jQuery Ajax是怎么解决的:html<!DOCTYPE html><html><head> <meta http-equiv="Content-Type" cont...https://blog.csdn.net/HerryDong/article/details/102580932

 

 (1)、login.aspx

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="login.aspx.cs" Inherits="login" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>接受和回传get/post参数</title>
   
</head>
<body> 
    接受和回传get/post参数

</body>
</html>


(2)、login.aspx.cs

using System;
using System.Collections.Generic;

using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class login : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {

    }

}

(3)、login.ashx

<%@ WebHandler Language="C#" Class="login_handle" %>

(4)、login.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Newtonsoft.Json;
using System.IO;
using Newtonsoft.Json.Linq;

    /// <summary>
    /// TestHandler 的摘要说明
    /// </summary>
    public class login_handle : IHttpHandler
    {
        public void ProcessRequest(HttpContext context)
        {
            context.Response.ContentType = "text/plain";

            // 将接收到的【JSON格式】转换成【字符串】

            string json = string.Empty;
            using (StreamReader reader = new StreamReader(context.Request.InputStream))
            {
                json = reader.ReadToEnd();
            } 
            
            // 获取json字符串中的键值项

            JObject jObject = JsonConvert.DeserializeObject(json) as JObject;

            // 获取:url地址方式中的id值
            
            string id = context.Request["id"];

            // 获取:username参数值,password参数值,message参数值

            string username = jObject["username"].ToString();
            string password = jObject["password"].ToString();
            string message = jObject["message"].ToString();

            context.Response.Write(JsonConvert.SerializeObject("后台已获取到:username:" + username + " | password:" + password + " | message:" + message));
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }

 【有坑请注意】:axios默认传参是json对象,不是字符串,解决方案可以参考上面的asp.net完整的前后端实例,也可以参考以下链接

VUE 之 Axios 的get和post前后端传参详解_小兔兔吃萝卜的博客-CSDN博客_axios的get怎么传输参数vue axios请求方式和传参格式http的get方法传递数组参数有两种形式形式一:通过逗号拼接query参数http://localhost:8080/api?arr=1,2,3,4&name=1 形式二:通过数组名+下标指定参数http://localhost:8080/api?arr[0]=1&arr[1]=2 使用axios的get方法传递数组参数形式一的解决方案// 这里注意使用+''将参数转换成了字符串,https://blog.csdn.net/qq_42552857/article/details/123639487

  • 1
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 3
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

敦厚的曹操

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值