首页 > 其他分享 > Vue3 使用 axios 实现跨域

Vue3 使用 axios 实现跨域

时间:2023-06-30 13:55:09浏览次数:37  
标签:vue 跨域 Vue3 axios 转发 请求 sina

Vue3 使用 axios 可以实现请求跨域问题

1.安装axios

npm install axios -S

2.引入axios 并配置为全局 $axios 对象

main.js

import { createApp } from 'vue'
import App from './App.vue'
import axios from 'axios'
 
//createApp(App).mount('#app')

const app = createApp(App)
app.config.globalProperties.$axios = axios

app.mount('#app')

2. 配置转发

下面代码是 将   127.0.0.1 的 8080端口  中凡是 含有 /sina 的地址  转发至 http://192.168.1.31:80/ 下

其中 /sina 不改变,只改变IP和端口

vue.config.js

const { defineConfig } = require('@vue/cli-service')
module.exports = defineConfig({
  transpileDependencies: true,

  //-----------------------Axios跨域请求-----------------------------------------
  devServer:{
    port:8080,//vue网页访问的端口
    host:"127.0.0.1",//vue网页访问的地址
    https:false,
    open:false,
    proxy: {
        '/sina': {  //为用于替换的的标识字符串
            target: 'http://192.168.1.31:80/',//Axios跨域请求的IP
            changeOrigin: true, 
            ws: true,
            pathRewrite: {
                '^/sina': '' //不改变
            }
        },
        /* 可以同步配置多个转发目标
        '/phpUrl': {  //为用于替换的的标识字符串
          target: 'http://192.168.1.8:8080/VueApi',//Axios跨域请求的IP
          changeOrigin: true, 
          ws: true,
          pathRewrite: {
              '^/phpUrl': '' //不用改
          }
       }  */
      
    }
  }
  //----------------------------------------------------------------------------

})

调用方式

其中地址   /sina/api/sessions  转发前 实际请求地址是  http://127.0.0.1:8080/sina/api/sessions

因为地址中 含有  /sina 符合转发条件 因此 axios 进行转发

转发后 实际请求地址是  http://192.168.1.31:80/sina/api/sessions

这样就实现了用 axios 进行 跨域转发 

且可以实现 当地址中不含 /sina 时正常请求,不进行转发

//axios 请求并 进行转发 -------------------------------------------------
//参数
var params=new URLSearchParams();
params.append('login',"admin");
params.append('password',"admin");
/**/
this.$axios.post('/sina/api/sessions', params)
    .then(response => {
        // 处理响应数据
        console.log(response.data);
        this.current_call_token= response.data.token;
        console.log(this.current_call_token);
    })
    .catch(error => {
        // 处理请求错误
        console.log(error);
    });

 

标签:vue,跨域,Vue3,axios,转发,请求,sina
From: https://www.cnblogs.com/hailexuexi/p/17516606.html

相关文章

  • Vue3 vite:is a JavaScript file. Did you mean to enable the 'allowJs' option?
    描述今天在vue3+vite下进行打包时,突然vscode报了一个error。 大概的意识是询问是否启用“allowJS”选项,因为该文件在程序内是指定用于编译的根文件。提示信息已经很明确了,下面从网上摘抄了下什么是allowJS选项。allowJs是1.8中新提供的选项。TypeScrip......
  • 第1节:vue3开发前准备
    (1)需要安装nodeJs版本16.0或以上版本     以下是2023年6月30日官方文档截图 (2)查看你的电脑里node版本 通过cmd命令查看node-v查看是否大于等于16 (3)创建vue项目注意:vue项目的命名不能用大写字母,只能小写字母,创建的项目名会以文件夹的方式呈现创建命令:cmd进......
  • Vue3 如何使用 axios
    在Vue3中集成和使用AxiosAxios是一个流行的JavaScript库,用于在浏览器和Node.js中进行HTTP请求。它提供了简洁的API,可以轻松地发送异步请求并处理响应数据。在Vue3中,我们可以使用Axios来与后端进行数据交互。 参考资料:Axios官方文档:GettingStarted| AxiosD......
  • 封装Axios
    Axios是一个基于Promise的易用、简洁且高效的HTTP请求插件,可以用于浏览器和Node.js。首先执行yarn命令安装依赖,安装成功时在package.json文件的dependencies下多出了Axios及其版本号,笔者写此书时,安装的版本为0.26.1,如所示。yarnaddaxiosAxios提供了一个配置灵活的API,可以传......
  • Vue3从入门到精通(三)
    vue3插槽Slots在Vue3中,插槽(Slots)的使用方式与Vue2中基本相同,但有一些细微的差异。以下是在Vue3中使用插槽的示例://ChildComponent.vue<template><div><h2>ChildComponent</h2><slot></slot></div></template>​//ParentComponent......
  • [vue3-print-nb]vue3中实现打印功能
    vue3安装npminstallvue3-print-nb--save项目中引入//全局引用import{createApp}from'vue'importAppfrom'./App.vue'importPrintfrom'vue3-print-nb'constapp=createApp(App)app.use(Print)app.mount('#app')//......
  • Vue3+Element-Plus安装及模拟增删改查
    软件安装:nodejs16https://nodejs.org/download/release/v16.20.0/将npm设置为淘宝镜像:npmconfigsetregistryhttps://registry.npm.taobao.org 创建vue3项目:npminitvue@latestEleement-Plushttps://element-plus.gitee.io/zh-CN/安装:npminstallelement-......
  • Nginx配置解决跨域问题
       server{      listen8080;      server_namelocalhost;       location/{         root/test;         indexindex.htmlindex.htm;          set$allow_cors0;         #判断不为空      ......
  • Asp.net OAuth2.0 跨域设置(可指定域名)
    第一步:Startup添加如下代码 第二步:功能实现///<summary>///跨域配置///</summary>publicclassCorsOriginsConfig{///<summary>///设置///</summary>publicstaticvoidSet(IAppBuilderapp)......
  • 光脚丫思考Vue3与实战:第05章 计算属性和侦听器 第03节 计算属性的其他玩法
    下面是本文的屏幕录像的在线视频:温馨提示:1、视频下载:线上视频被压缩处理,可以下载高清版本:链接:https://pan.baidu.com/s/1h600_BRR9O2Lr87zVQNgEw 提取码:dgpu 2、示例代码:https://pan.baidu.com/s/1rCqbY_j35FcRWRZbuOfHqg 提取码:79kh 下图是文章大纲:一、概述本篇文章介绍了V......