Vue2Vue3代理配置 安装 axios 和使用

1最开始一直提示400错误,根据下面的测试可成功安装

1、查看代理设置执行,不为null时设置为空:
npm config get proxy
npm config get https-proxy
如果返回值不为null,继续执行:
(这一步很重要,一定要保证两个命令的返回值都为null)
npm config set proxy null
npm config set https-proxy null
2、执行:
npm config set registry http://registry.cnpmjs.org/

2安装axios

npm install axios

3.设置代理服务器,可发送请求和解决跨域问题,跨域可通过(cors,jsonp,代理服务器)现在通过cli的代理服务器实现ajax请求。

   一般使用多个后台实现方式。

vue.config.js
module.exports = defineConfig({
  transpileDependencies: true,
  //使用cli 脚手架 配置一个代理服务器 可解决跨域问题。
  //一个后台源
   devServer: {
     proxy: 'http://localhost:1230'
   }
  //多个后台源
  devServer: {
    proxy: {
      '/api': {
        target: 'http://localhost:1230',
        pathRewrite:{'^/api':''},//替换路径中的/api
        ws: true,
        changeOrigin: true,//高速服务器请求的端口号是真的还是
      },
      '/foo': {
        target: 'http://localhost:1230'
      }
    }
  }

})

发送请求

<script>
import f from '@/Content/php'//默认暴露
import axios from 'axios';//引用axios
export default {
  name: 'myMsg',
  data() {
    return { Message: '' };
  },
  methods: {
    GetStudents:function(){
        f.funHello1('php');
        f.funHello2('张三');
    },
    Getaxiosfun:function(){
        //使用axios
        axios.get('http://localhost:8080/api/Home/GetStudents').then(
            response=>{alert(this.Message=response.data)},//成功回调
            error=>{alert(this.Message=error.message)},//失败回调
        );
    }
  },
};
</script>

Post

Postaxiosfun:function(){
        //使用post
        axios.post('http://localhost:8080/api/Home/GetStudents2',{name:'0123456'}).then(
            response=>{
                alert(this.Message=response.data)
            },//成功回调
            error=>{
                alert(this.Message=error.message)
            },//失败回调
        );
    }

c#接口

 [HttpGet]
        public string GetStudents(string name) {
            return 'get:' + name;
        }
        [HttpPost]
        public string GetStudents2(string name)
        {
            return 'post:'+name;
        }

VU3 服务代理配置

调用时的端口看浏览器项目的端口。

import { fileURLToPath, URL } from 'node:url'
import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'
// https://vitejs.dev/config/
export default defineConfig({
  plugins: [vue()],
  resolve: {
    alias: {
      '@': fileURLToPath(new URL('./src', import.meta.url))
    }
  },
  server:{
    port:5176,//留意看vue项目浏览器的端口是没是
    open:true,
    proxy:{
      '/api': {
        target: 'http://172.16.6.133:83',
        changeOrigin: true,
        rewrite: (path) => path.replace(/^\/api/, ''),
      },
      '/php': {
        target: 'http://172.16.6.133:83',
        changeOrigin: true,
        rewrite: (path) => path.replace(/^\/php/, ''),
      },
    }
  }
})

调试找到文件路径下的vue组件下调试

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值