06-vue-cli -axios モジュールとドメイン プロキシ

1. vue-axios の概要

        Vue.js バージョン 2.0 では、axios を使用して ajax リクエストを完了することを推奨しています。

        Axios は、ブラウザーと Node.js で使用できる Promise ベースの HTTP ライブラリです。

1.1 新機能

ブラウザから XMLHttpRequest を作成する

Node.jsからhttpリクエストを作成する

リクエストとレスポンスをインターセプトする

リクエストデータとレスポンスデータを変換する

キャンセルリクエスト

JSONデータを自動変換する

1.2. インストール

1 つ目: インポート

2 番目: npm を使用します:

        npm インストール axios

1.3. vue-axios-get リクエスト

  1. main.jsに導入され、グローバル変数を設定します
// 导入axios的模块
import axios from 'axios'

    
//设置axios的全局变量
Vue.prototype.$http=axios;

2. vue-axios-get リクエストの構文

axios.get("请求地址",{ 
    params:”请求参数对象” 
    }).then(function(rs){ //成功返回函数 
    console.log(rs) 
    }) 

3. vue-axios-get リクエストの実装

<template>
  <div>
    <button type="button" @click="test02">跨域请求演示</button>
  </div>
</template>

<script>
    export default{
    name:"testAjax",
    methods: {
        test02(){//get请求
              this.$http.get(
                    "/testAjax/test01",
                    {params:{"name" : "rock"}}
              ).then(function(rs){
                console.log(rs);
              }).catch(function(rs){
                console.log("服务器连接错误");
              })
    
       },
     }
  }
</script>

<style>
</style>

1.4 vue-axios-post リクエスト

1. main.jsに導入し、グローバル変数を設定する

// 导入axios的模块
import axios from 'axios'
//导入qs模块
import qs from 'qs'

//设置axios的全局变量
Vue.prototype.$http=axios;

//设置qs的全局变量
Vue.prototype.$qs = qs;

Vue.config.productionTip = false

2. vue-axios-get リクエスト、2 つの書き方

最初

<template>
  <div>
    <button type="button" @click="test03">跨域请求演示</button>
  </div>
</template>

<script>
    export default{
    name:"testAjax",
    methods: {
         test03(){//post请求
          this.$http.post(
                "/testAjax/test02",
                this.$qs.stringify({"name" : "rock"})
          ).then(function(rs){
            console.log(rs);
          }).catch(function(rs){
            console.log("服务器连接错误");
          })
      },
     }
  }
</script>

<style>
</style>

二番目

2. vue-cli ドメイン名エージェント

1. プロキシとは何ですか

        プロキシ サーバーの英語の正式名は Proxy Server で、その機能はネットワーク ユーザーがネットワーク情報を取得するエージェントとして機能することです。わかりやすく言えば、ネットワーク情報の中継点です。できる

        単純かつ大まかに理解すると、自分のドメイン名を、アクセスしたドメイン名に変換し、同じソースを形成すれば、それにアクセスできるようになります。

2. プロキシを使用する理由

        フロントエンドとバックエンドを別々に開発することは、クロスドメインの問題の解決とは切り離せないものであり、プロキシはフロントエンドがクロスドメインの問題を解決するための手段です。

3. クロスドメインとは

        リクエスト URL のプロトコル、ドメイン名、ポートのいずれかが現在の URL と異なる場合、それはクロスドメインです。

  1. 現在のページ URL 要求されたページ URL がクロスドメインであるかどうか http://www.test.com/         
  2. http://www.test.com/index.html いいえ 同じソース (同じプロトコル、ドメイン名、ポート番号) http://www.test.com/         
  3. https://www.test.com/index.html さまざまなクロスドメイン プロトコル (http/https)
  4. http://www.test.com/ http://www.baidu.com/ クロスドメインのプライマリ ドメイン名が異なります (test/baidu) http://www.test.com/
  5. http://blog.test.com/ さまざまなクロスドメイン サブドメイン (www/blog)

4. 非相同制限

[1] 異なるオリジンの Web ページから Cookie を読み取ることができません

[2] 非同一オリジンWebページのDOMにアクセスできない

[3] AJAX リクエストは同一オリジン以外のアドレスには送信できません

5. クロスドメインの問題を解決する方法

5.1. 最初のタイプ: サーバー側で解決する

以下のように設定します

.springboot クロスドメイン構成

以下は springboot のクロスドメイン構成クラスです。springboot のバージョンは 2.4 より前のバージョンである必要があります。

package com.hqyj.config;

import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

@Configuration
public class CrossConfig implements WebMvcConfigurer {

    @Override public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**")/*所有的当前站点的请求地址,都支持跨域访问*/
                .allowedOrigins("*")/*所有的外部域都可跨域访问*/
                .allowedMethods("GET","HEAD","POST","PUT","DELETE","OPTIONS")/*哪些请求 需要跨 域配置*/
                .allowCredentials(true) /*是否支持跨域用户凭证*/
                .maxAge(300)/*超时时长设置为5分钟。 时间单位是秒。*/
                .allowedHeaders("*");/*请求体的头部*/ }
}

5.2 2 番目の方法: フロントエンド ソリューションを使用する

次のように進めます。

1: config ディレクトリの下のindex.js ファイルで、コード proxyTable の 13 行目に構成を追加します。コードは次のとおりです。

assetsPublicPath: '/',
      proxyTable: { //设置域名代理
        "/exam":{
          target:"http://localhost:8080",//代理服务器地址
          secure:false,//如果是https接口,需要配置这个参数值为 true
          ws: true,//是否代理websockets
          changeOrigin: true,//允许跨域访问 后端地址
          pathRewrite: {'^/exam': ''} ,
          }
      },

可以配置多个域名代理

2 main.jsでaxiosのグローバル設定を設定する

import Vue from 'vue'
import App from './App'
import router from './router'
// 导入axios的模块
import axios from 'axios'
//导入qs模块
import qs from 'qs'

//设置axios模块默认的url代理的服务器
axios.defaults.baseURL = '/exam'

//设置session的跨域配置
axios.defaults.withCredentials=true

//设置axios的全局变量
Vue.prototype.$http=axios;

//设置qs的全局变量
Vue.prototype.$qs = qs;

Vue.config.productionTip = false

/* eslint-disable no-new */
new Vue({
  el: '#app',
  router,
  components: { App },
  template: '<App/>'
})

3 上記の 2 つの手順を構成した後、次の方法でプロジェクトを作成できます。

1.新しいtestAjax.vue

2. src/routerの下のindex.jsにtestAjaxコンポーネントを導入します。

import Vue from 'vue'
import Router from 'vue-router'
/*  配置地址,叫组件
    第一种:导入hello组件
*/
// import hello from '../components/demo/hello.vue'

/*
    第二种:导入hello组件
*/
import hello from  '@/components/demo/hello'

/*  配置地址,叫组件
    第一种:导入hello01组件
*/
import hello01 from '../components/demo/hello01.vue'

import testAjax from '../components/demo/testAjax.vue'

Vue.use(Router)

export default new Router({
  routes: [
    {
      /* 斜杠:代表项目的默认地址 */
      path: '/',
      name: 'hello',  /* 组件名称:保持名称唯一性 */
      component: hello  /*  引入组件的别名   */
    },
    {
      path: '/hello01',
      name: 'hello01',
      component: hello01
    },
    {
      path: '/testAjax',
      name: 'testAjax',
      component: testAjax
    },
  ]
})

1: コードの実装

1. フロントエンド

投稿リクエスト: test03 | 取得リクエスト: test01 test02

<template>
  <div>
    <button type="button" @click="test01">跨域请求演示</button>
    <button type="button" @click="test02">跨域请求演示</button>
      <button type="button" @click="test03">跨域请求演示</button>
  </div>
</template>

<script>

  export default{
    name:"testAjax",
    methods: {
      test01() {   //跨域请求演示
        $.ajax({
          url: "/exam/testAjax/test01",
          type: "get",
          data:
          {
            "name" : "rock"
          },
          success: function(rs){
            console.log(rs);
          },
          error: function(rs){
            console.log("服务器连接错误");
          }
        })
      },
      test02(){//get请求
          this.$http.get(
                "/testAjax/test01",
                {params:{"name" : "rock"}}
          ).then(function(rs){
            console.log(rs);
          }).catch(function(rs){
            console.log("服务器连接错误");
          })

      },
      test03(){//post请求
          this.$http.post(
                "/testAjax/test02",
                this.$qs.stringify({"name" : "rock"})
          ).then(function(rs){
            console.log(rs);
          }).catch(function(rs){
            console.log("服务器连接错误");
          })
      },
    }
  }
</script>

<style>
</style>

2. バックエンド

スプリングブートプロジェクトを作成する

1. pom は初期化された pom の後に続きます

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.6.11</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.hqyj</groupId>
    <artifactId>idea_vue</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>idea_vue</name>
    <description>Demo project for Idea Vue</description>
    <properties>
        <java.version>1.8</java.version>
    </properties>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>

2. コントローラー パッケージを作成し、新しい TestAjaxController.java を作成し、対応するインターフェイスを記述します

package com.hqyj.controller;

import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/testAjax")
public class TestAjaxController {


    @GetMapping("/test01")
    public String test01(String name){
        System.out.println("name="+name);
        return "hello";
    }

    @PostMapping("/test02")
    public String test02(String name){
        System.out.println("name="+name);
        return "hello";
    }

}

おすすめ

転載: blog.csdn.net/weixin_46048259/article/details/127461893