我正在开发一个简单的应用程序,以 React 作为客户端应用程序,以 ASP.NET Core 作为服务器。但是,当我尝试从 React 客户端向 ASP.NET Core 服务器发送 POST 请求时,我遇到了以下 CORS 错误:
localhost/:1 访问 XMLHttpRequest 来自原点的“http://localhost:5094/api/records” “https://localhost:44477”已被 CORS 策略阻止:响应 预检请求未通过访问控制检查:重定向未通过 允许预检请求。
我已经在 Program.cs 文件中的 ASP.NET Core 后端配置了 CORS:
using Microsoft.EntityFrameworkCore;
using Npgsql.EntityFrameworkCore.PostgreSQL;
using NET_REACT.Context;
var builder = WebApplication.CreateBuilder(args);
// Add services to the container.
builder.Services.AddCors(o =>
{
o.AddDefaultPolicy(
builder =>
{
//you can configure your custom policy
builder.WithOrigins("https://localhost:44477")
.AllowAnyMethod()
.AllowAnyHeader();
});
});
builder.Services.AddControllersWithViews();
// Add services to the container.
builder.Services.AddControllersWithViews();
builder.Services.AddDbContext<MyDbContext>(
o => o.UseNpgsql(builder.Configuration.GetConnectionString("MyPostgresConnection"))
);
var app = builder.Build();
// Configure the HTTP request pipeline.
if (!app.Environment.IsDevelopment())
{
// 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();
app.UseCors();
app.MapControllerRoute(
name: "default",
pattern: "{controller}/{action=Index}/{id?}");
app.MapFallbackToFile("index.html");
app.Run();
在 React 客户端中,我使用 Axios 发送 POST 请求,如 App.js 文件中所示:
import React, { useState } from 'react';
import axios from 'axios';
const App = () => {
const [Name, setName] = useState('');
const [Email, setEmail] = useState('');
const handleSubmit = async (e) => {
e.preventDefault();
try {
const response = await axios.post('http://localhost:5094/api/records', { Name, Email });
console.log(response.data);
} catch (error) {
console.error('Error:', error.message);
}
};
return (
<div>
<h1>Send POST Request</h1>
<form onSubmit={handleSubmit}>
<div>
<label>Name: </label>
<input type="text" value={Name} onChange={(e) => setName(e.target.value)} />
</div>
<div>
<label>Email: </label>
<input type="email" value={Email} onChange={(e) => setEmail(e.target.value)} />
</div>
<button type="submit">Submit</button>
</form>
</div>
);
};
export default App;
如果您能提供有关如何解决此 CORS 问题并成功将 POST 请求从我的 React 客户端发送到 ASP.NET Core 服务器的见解或建议,我将不胜感激。谢谢!
您确定网址正确吗?这似乎是错误的,因为你给了 https:// 链接到 cors 但反应不运行 https 并且你给了 api 到 http:// 但.net core 通常有默认的 SSL 你可以检查它吗?否则允许所有IP:
var MyAllowSpecificOrigins = "_myAllowSpecificOrigins";
builder.Services.AddCors(options => options.AddPolicy(name: MyAllowSpecificOrigins,
policy =>
{
policy.AllowAnyOrigin()
.AllowAnyMethod()
.AllowAnyHeader();
}
));
app.UseCors(MyAllowSpecificOrigins);