.net core3.1 webapi + vue.js + axios cross-domain

I want to talk about is based on webapi projects under .net core3.1 environment, how to use the front of the docking axios vue project

Since talking about axios, official document posted here axios the address:

http://www.axios-js.com/zh-cn/docs/

First, the front end portion set

The first step in installing axios vue project

 

 Enter the command in the terminal vs code npm install axios

Wait a moment to complete the installation

The second step, to build axios test api

Main.js the first need, mounted in front of the introduction axios

 

 

 

Then hook function in a component, write the following code

 

 

When the component is created, send a request to get back, get the data. If api for axios not familiar, you can go to axios official documents

Of course, I was a novice in advance ready for shots, for inspection

 

 

 This picture above official documents from axios

This completes the front part

The next project is to configure the .net core webapi

In fact, the back-end configuration is extremely simple, just enable cors, and then do some service injection and middleware can add

Microsoft's document also gives this part of the relevant notes, where you can choose to view Microsoft's official documentation

The first step, service injection

Add the following code startup.cs

 

 

readonly string MyAllowSpecificOrigins = "_myAllowSpecificOrigins";

 

#region cors
services.AddCors(options =>
{
options.AddPolicy(MyAllowSpecificOrigins,
builder =>
{
builder.WithOrigins("http://localhost:8888")
.AllowAnyHeader()
.AllowAnyMethod();
});
});
#endregion

注意WithOrigins方法表示的允许跨域访问的url,参数可以是一个数组的形式,比如像下面这种方式去写:

 

 第二步,添加中间件

 

 这里按照微软的官方文档,cors的中间件放置需要特别注意位置,这里面我是放在了UseRouting与UseEndPoints的中间,这个可以参照微软的文档,里面有注解

第三步,在控制器上打上标签

 

  [EnableCors(PolicyName = "_myAllowSpecificOrigins")]

到此,前后端的配置都已结束,接下来让我们见证最终的效果

 

 完美响应,so good

Guess you like

Origin www.cnblogs.com/shapman/p/12232868.html