我尝试使用 Postman 添加新成员,结果成功了。但我的网站却没有,当我尝试在我的网站上提交新用户时,出现了下面的控制台错误:
从源“http://localhost:3000”访问“http://localhost:5243”处的 XMLHttpRequest 已被 CORS 策略阻止:请求的资源上不存在“Access-Control-Allow-Origin”标头。未检查的runtime.lastError:侦听器通过返回 true 指示异步响应,但消息通道在收到响应之前关闭
我按照本文中的说明修改了program.cs,但没有成功:How to fix CORS error: MethodDisallowedByPreflightResponse in ASP .NET C#
以下是program.cs和memberadd.jsx代码:
//Program.cs:
var policyName = "AllowLocalhost3000"; //
var builder = WebApplication.CreateBuilder(args);
// Add CORS policy to allow requests from 'http://localhost:3000'
builder.Services.AddCors(options =>
{
options.AddPolicy(name: policyName,
policyBuilder =>
{
policyBuilder.WithOrigins("http://localhost:3000")
.AllowAnyHeader()
.AllowAnyMethod()
.AllowCredentials()
.WithExposedHeaders("Access-Control-Allow-Origin", "http://localhost:3000")
.SetIsOriginAllowed((host) => true);
});
});
builder.Services.AddControllers();
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();
var app = builder.Build();
app.UseCors(policyName);
if (app.Environment.IsDevelopment())
{
app.UseSwagger();
app.UseSwaggerUI();
}
app.UseHttpsRedirection();
app.UseAuthorization();
app.MapControllers();
app.Run();
//MemberAdd.jsx:
try {
const response = await axios.post(
`http://localhost:5243/MemberFirstName=${encodeURIComponent(member.firstName)}&LastName=${encodeURIComponent(member.lastName)}&DOB=${encodeURIComponent(member.dob)}&email=${encodeURIComponent(member.email)}`
);
if (response.status === 200) {
alert("Member Added!");
clearForm();
} else {
alert("Failed to add member.");
}
} catch (error) {
console.error("Error adding member: ", error);
alert("An error occurred while adding the member.");
}
.WithExposedHeaders("Access-Control-Allow-Origin", "http://localhost:3000")
用于向客户端公开某些响应标头,但设置 Access-Control-Allow-Origin 不需要它
最多出于安全原因,您应该尝试将数据作为 JSON 对象而不是查询参数传递,同时也更符合 REST 原则。
最后一件事,确保控制器中的接收者方法用 [HttpPost] 装饰