我构建了一个极其简单的“hello world”等价的 Web API 代码,以确保我的连接正常工作。
[AllowAnonymous]
[HttpPost]
[Route("BaseTest")]
public async Task<string> BaseTest()
{
return "TESTING";
}
还有从该 API 获取的 Vue 3 前端
fetch('https://localhost:7209/MapData/BaseTest', {
method: 'POST',
headers: {
"Content-Type": "application/json",
"x-access-token": "token-value",
},
crossorigin: true,
mode: 'no-cors',
}).then(response => alert(response));
响应是一个响应对象。状态为 null,ok 为 false,类型为 opaque。
当我在邮递员中执行相同的 post 调用时,我收到了字符串“TESTING”,如预期的那样。
我应该检查什么和/或我的错误是什么?
我希望有一个非常简单、非常容易完成的“Hello World”等价物,在 Vue 3 应用程序上收到“TESTING”。相反,它惨遭失败。
我尝试通过以下方式访问响应数据:
response.text()
response.json()
我已确认回复已返回:
ok = false
type = opaque
status = ''
statusText = ''
我尝试捕获任何可能抛出的错误,但没有收到任何错误。
我尝试过将Web API调整为同步或返回ActionResults,但都不起作用。
我已经验证,在对此 URL 进行 POST 调用时,swagger 测试页面和邮递员都能够接收简单的“TESTING”响应。
编辑1: 我已经调整了我的代码以尝试以下操作:
C# 端点 尝试 #1:
...
[EnableCors("LocalHostOrigins")]
[AllowAnonymous]
[HttpPost]
[Route("BaseTest")]
public async Task<String> BaseTest()
{
return "TESTING";
}
...
C# Program.cs 尝试 #1:
builder.Services.AddCors(options =>
{
options.AddPolicy(name: LocalHostOrigins,
policy =>
{
policy.WithOrigins("https://localhost:5173", "http://localhost:*");
});
options.AddPolicy(name: AllOrigins,
policy =>
{
policy.WithOrigins("*");
});
});
...
app.UseCors();
C# 端点 尝试 #2:
[EnableCors]
[AllowAnonymous]
[HttpPost]
[Route("BaseTest")]
public async Task<String> BaseTest()
{
return "TESTING";
}
C# Program.cs 尝试 #2:
builder.Services.AddCors(options =>
{
options.AddDefaultPolicy(policy =>
{
policy.WithOrigins("*:*");
});
});
...
app.UseCors();
C# 端点 尝试 #3:
[EnableCors]
[AllowAnonymous]
[HttpPost]
[Route("BaseTest")]
public async Task<String> BaseTest()
{
return "TESTING";
}
C# Program.cs 尝试 #3:
builder.Services.AddCors(options => {});
...
app.UseCors(builder =>
{
builder.AllowAnyOrigin()
.AllowAnyMethod()
.AllowAnyHeader();
});
...
Vue3 Web 应用程序,在所有场景中:
...
fetch('https://localhost:7209/MapData/BaseTest')
.then(response => alert(response)); // [object Response]
fetch('https://localhost:7209/MapData/BaseTest')
.then(response => alert(response.text())); // [object Promise]
fetch('https://localhost:7209/MapData/BaseTest')
.then(response => response.text())
.then(data => alert(data)); // empty string
...
我目前担心的是,即使在 CORS 似乎按预期和期望运行的情况下,我的请求仍然会带有空数据。
我使用下面的代码进行测试,没有遇到同样的问题。
如果我评论
app.UseCors("CorsPolicy");
,我的页面应该有如下的cors问题。使用catch可以捕获错误。
成功图
完整代码
测试API.vue
<template>
<div>
<button @click="testApi">Test API</button>
<p v-if="apiResponse">{{ apiResponse }}</p>
<p v-if="error">{{ error }}</p>
</div>
</template>
<script>
export default {
data() {
return {
apiResponse: null,
error: null,
};
},
methods: {
testApi() {
fetch('https://localhost:7180/BaseTest', {
method: 'POST',
headers: {
"Content-Type": "application/json",
"x-access-token": "token-value",
},
})
.then(response => {
if (!response.ok) {
throw new Error('Network response is not ok');
}
return response.text();
})
.then(data => {
this.apiResponse = data;
})
.catch(error => {
console.error('API Invoke Error:', error);
this.error = error.stack;
});
},
},
};
</script>
程序.cs
namespace WebApplication1
{
public class Program
{
public static void Main(string[] args)
{
var builder = WebApplication.CreateBuilder(args);
// Add services to the container.
builder.Services.AddControllersWithViews();
// allow all Origin
builder.Services.AddCors(options => options.AddPolicy("CorsPolicy", builder =>
{
builder.AllowAnyMethod()
.SetIsOriginAllowed(_ => true)
.AllowAnyHeader()
.AllowCredentials();
}));
var app = builder.Build();
// Configure the HTTP request pipeline.
if (!app.Environment.IsDevelopment())
{
app.UseExceptionHandler("/Home/Error");
// The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
// add this line
app.UseCors("CorsPolicy");
app.UseAuthorization();
app.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}");
app.Run();
}
}
}