[英]VueJs + ASP.Net Core Web API Make a post request
I have a VueJs Frontend where I want to make a post request to my ASP.NET Core Web API.我有一个 VueJs 前端,我想在其中向我的 ASP.NET Core Web API 发出发布请求。 This is what the code in the VueJs app looks like: VueJs 应用程序中的代码如下所示:
methods: {
async addProject(project){
const res = await fetch('https://localhost:44357/test/data/CreateProject', {
method: 'POST',
headers: {
'Content-type': 'application/json'
},
//mode: 'no-cors',
body: JSON.stringify(project)
})
const data = await res.json()
this.projects = [...this.projects, data]
},
},
The url could be missleading so I want to clarify that this url is mapped inside the Web API to a method inside the controller which should get a project object which has only a name attribute in it.该 url 可能具有误导性,所以我想澄清一下,这个 url 在 Web API 内部映射到控制器内部的方法,该方法应该获取一个只有 name 属性的项目对象。
Now for the ASP.NET Core Web API I have set up cors so that I can make calls to it:现在对于 ASP.NET Core Web API,我已经设置了 cors 以便我可以调用它:
services.AddCors();
...
app.UseCors(
options => options.WithOrigins("http://localhost:8080").AllowAnyMethod()
);
Now for the route mapping I did it like this:现在对于路由映射,我是这样做的:
endpoints.MapControllerRoute(
name: "test",
pattern: "test/data/CreateProject",
defaults: new { controller = "Models", action = "createproject" }
);
//the function:
[HttpPost]
public string CreateProject([FromBody] Project data)
{
Debug.WriteLine(data.Name);
return "Ok";
}
Now the error that I get is that I cannot make a call because of cors policy which is weird for me.现在我得到的错误是我无法打电话,因为 cors 政策对我来说很奇怪。 I thought I allowed the vuejs app to make calls.我以为我允许 vuejs 应用程序拨打电话。 I then installed the chrome plugin CORS unblock which didnt solve this basically but in the network tab inside the website inspector I can see that there is a Post Request with status code 204. I just want to confirm that the data arrives in my Web Api.然后我安装了 chrome 插件 CORS unblock,它基本上没有解决这个问题,但是在网站检查器内的网络选项卡中,我可以看到有一个状态代码为 204 的 Post Request。我只想确认数据是否到达我的 Web Api。 What am I doing wrong and what do I need to change in order to make this happen?我做错了什么,我需要改变什么才能做到这一点?
app.UseCors(
options => options.WithOrigins("http://localhost:8080").AllowAnyMethod().AllowAnyHeader()
);
Using AllowAnyHeader function fixed it使用 AllowAnyHeader 功能修复它
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.