Vue前台请求后台数据采坑日志,包含传递json数据

第一个坑,跨域问题,由于.net webapi与Vue服务器不在同一机器上ip端口都不一样,需要配置跨域,但总说找不到.devServer

解决过程异常艰辛,原因诡异,解决办法如下

需要将xxxx.config.js修改名称为vue.config.js
还要用管理员运行PowerShell然后输入
set-ExecutionPolicy RemoteSigned
输入Y
回车才可以

main.js

import Vue from 'vue'
import App from './App.vue'
import axios from 'axios'

Vue.prototype.$axios = axios;
Vue.config.productionTip = false

new Vue({
  render: h => h(App),
}).$mount('#app')

App.vue


 

第二个坑,axios需要设置成post否则后台body中没有数据,而postman用get和post后台都没有问题

[HttpPost("velocity")]

第三个坑,前台通过body传递json参数,后台用实体接收,postman没有问题,vue死活不行,原因是json数据的格式不对称

前台可以通过下面输出来看是不是想要的格式

console.log(JSON.stringify(obj));
console.log(this.$qs.stringify(obj));
console.log(this.$qs.parse(obj));

后台直接用流接收,然后看输出是不是想要的

        [HttpPost("velocity")]
        public ActionResult GetVelocity()
        {
            Stream stream = Request.Body;
            FlowVelocity flowVelocity = new FlowVelocity();
            string data = "";
            if (stream != null)
            {
                using (var reader = new StreamReader(stream, Encoding.UTF8))
                {
                    data = reader.ReadToEnd();
                }
            }
            Console.WriteLine(data);
            return 1;
        }

可以正常交汇的代码示例

前端


 

后端

[HttpPost("velocity")]
public ActionResult GetVelocity(FlowVelocity flowVelocity)
{
    return flowVelocity.GetV();
}

实体类

   public class FlowVelocity
    {
        public double R { get; set; }//半径(米)
        public double Q { get; set; }//流量(立方米每秒)
        public double V { get; set; }//流速(米每秒)
        public double GetV()
        {
            double v = (Q / (Math.PI * Math.Pow(R, 2))) / 3600;
            return v;
        }
    }

 

你可能感兴趣的:(WEB开发,.Net)