ホームページ  >  記事  >  ウェブフロントエンド  >  springboot と element-axios がクロスドメインリクエストを実装する方法 (コード)

springboot と element-axios がクロスドメインリクエストを実装する方法 (コード)

不言
不言オリジナル
2018-09-14 17:44:133416ブラウズ

この記事の内容は、springboot と element-axios がクロスドメイン リクエスト (コード) を実装する方法に関するものです。必要な方は参考にしていただければ幸いです。

1. 要素プロジェクトを初期化します
1.1: vue init Web ページ 'プロジェクト名'
1.2: npm i element-ui -S
1.3: main.js 内

import ElementUI from 'element-ui'
import 'element-ui/lib/theme-chalk/index.css'
Vue.use(ElementUI)

2 を追加します。 axios クロスドメイン リクエストを追加します。

main.js に

/**
  * 跨域设置
  * @type {AxiosStatic}
  */
  import axios from 'axios'
  Vue.prototype.$axios = axios
  Vue.config.productionTip = false
  axios.defaults.withCredentials = false//这个默认即为false,如果改为true,可以传递session信息,后端要做相应修改来放行,
# を追加します。

##3. ページを作成します#

<template>
  <el-button @click="post">发送请求</el-button>
</template>

<script>
  import axios from "axios";
  export default {

    data() {
      return {
        activeIndex2: &#39;1&#39;
      };
    },
    methods: {
      handleSelect(key, keyPath) {
        console.log(key, keyPath);
      },
      post(){
        axios.get(&#39;http://localhost:8080/test&#39;)
          .then(function (response) {
            console.log(response,"已经成功发送请求!");
          })
          .catch(function (error) {
            console.log("请求失败!");
          });
      }


    }
  }
</script>
#4. springboot プロジェクトを作成します

#4.1 コントローラー クラスを追加します

@Controller
@CrossOrigin
public class TestController {
    @RequestMapping("/test")
    @ResponseBody
    public JsonResponseExt Test(){
        System.out.println("在执行~~~~~~~~~");
        return JsonResponseExt.success("执行");
    }

}

JsonResponseExt は自分でカプセル化したクラスです。オブジェクトまたは文字列を直接返すことができます。さらに、@CrossOrigin アノテーションをコントローラー クラスに追加する必要があります。そうしないと、フロントエンドの結果が返されます。エラーを報告する


設定クラスを自分でカプセル化することもできます (例:

@Configurationpublic class CorsConfig  extends WebMvcConfigurerAdapter {

    @Override    public void addCorsMappings(CorsRegistry registry) {
        System.out.println("----------------------");
        registry.addMapping("/**")
                .allowedOrigins("*")
                .allowCredentials(true)
                .allowedMethods("GET", "POST", "DELETE", "PUT")
                .maxAge(3600);
    }


}

5、テスト結果

#)

#関連する推奨事項:

axios リクエストがドメインを越える方法

vue-cli axios リクエストとクロスドメイン######

以上がspringboot と element-axios がクロスドメインリクエストを実装する方法 (コード)の詳細内容です。詳細については、PHP 中国語 Web サイトの他の関連記事を参照してください。

声明:
この記事の内容はネチズンが自主的に寄稿したものであり、著作権は原著者に帰属します。このサイトは、それに相当する法的責任を負いません。盗作または侵害の疑いのあるコンテンツを見つけた場合は、admin@php.cn までご連絡ください。