Vuejsとaxiosを使って、WebApiと連携してみた
背景
Web系ではjQueryとASP.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経由で取得)
サーバー側
ソースコード
フロントエンド側
<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」に設定されれば正常