やっぱりエンジニア

ITエンジニアとして思ったことや、日常起こったことを書くブログです。

Vuejsとaxiosを使って、WebApiと連携してみた

背景

Web系ではjQueryASP.NET WebApiでのAjax連携を行ったことがあるが、vue.jsのようなjavascriptフレームワークを使ったことがなかった。
ASP.NETがメインであるため、今後もOSSフレームワークを業務で触る機会がないので、自分で勉強をしてみたいと感じた。
以前、DataBindモデルのKnockOut.jsを使ってみたが、文献も英語が多いため、挫折。
似たような?Vuejsがトレンドになってきて、学習コストが低いみたなので、
Vuejsを勉強する。

実施事項

Vuejsとaxiosを使って、ASP.NET WebApiと連携をしてみる。
 

詰まった所

クライアントとサーバーが別ドメインだったのでCORSで多少手間取った。
 今回はサーバー側にCORSの設定をした。

環境

クライアント側

IDE:VisualStudioCode(Vetur、ESLint、HTMLHint、LiveServerを導入)
フレームワーク:Vuejs、axios(CDN経由で取得)
 

サーバー側

IDE:VisualStudio2017 Community
フレームワークASP.NET WebApi Core

ソースコード

フロントエンド側

<html>
<!DOCTYPE html>
<html lang="ja">

<head>
    <meta charset="UTF-8">
    <title>Document</title>
    <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/axios/0.18.0/axios.min.js"></script>
</head>

<body>
    <div id="app">
        <p>{{apidata}}</p>
        <button v-on:click="connectApi">API連携</button>
    </div>
    <script>
        var app = new Vue({
            el: "#app",
            data: {
                apidata: "",
                url: "http://localhost:61782/api/values"
            },
            methods: {
                connectApi: function () {
                    self = this;
                    axios.get(this.url)
                        .then(function (res) {
                            self.apidata = res.data[0];
                            console.log(res.data);
                        });
                }
            }
        });
    </script>
</body>

</html>
</html>

C#

サーバー側はASP.NET CoreのAPIプロジェクトを選択しました。
CORS設定以外はデフォルトのままです。
docs.microsoft.com

valuesControlles.cs

using System.Collections.Generic;
using Microsoft.AspNetCore.Mvc;

namespace WebApiCore.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class ValuesController : ControllerBase
    {
        // GET api/values
        [HttpGet]
        public ActionResult<IEnumerable<string>> Get()
        {
            return new string[] { "value1", "value2" };
        }
    }
}

Startup.cs

using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;

namespace WebApiCore
{
    public class Startup
    {
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        readonly string MyAllowSpecificOrigins = "_myAllowSpecificOrigins";

        public IConfiguration Configuration { get; }

        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddCors(options =>
            {
                options.AddPolicy(MyAllowSpecificOrigins,
                builder =>
                {
                    //LiveServerで立ち上がったurlを設定(ポートを入れないと動きませんでした。)
                    builder.WithOrigins("http://127.0.0.1:5500");
                });
            });

            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseHsts();
            }

            app.UseCors(MyAllowSpecificOrigins);

            app.UseHttpsRedirection();
            app.UseMvc();
        }
    }
}

結果

タグに文字列「value1」に設定されれば正常

考察

アプリとしては何でもないが、C#とvue.js連携を行いました。
業務でトレンド的な組み合わせのフレームワークを扱う機会がないので、どう勉強していくか悩む