我想要从一个使用REACT编写的前端表单向一个使用C#编写的API服务器POST数据。
为此,我编写了以下内容: 对于前端:
针对后端:
然而,我有以下问题: 我尝试了很多不同的配置,但都没有成功。有没有人知道问题在哪里,怎么解决?
提前感谢, Alexia
[版面]
根据所有建议,我改变了我的代码。
前端部分:
使用这个配置,我仍然有:
为此,我编写了以下内容: 对于前端:
const [analysis, setAnalysis] = useState(null);
const headers = {
'Content-Type': 'application/json;charset=UTF-8',
"Access-Control-Allow-Origin": "*",
'Access-Control-Allow-Methods': 'GET, PUT, POST, DELETE, OPTIONS',
'Access-Control-Allow-Headers': '*'
};
useEffect(() => {
axios.get(baseURL, {
mode: 'cors',
headers: headers,
}).then((response) => {
setAnalysis(response.analysis);
});
}, []);
针对后端:
builder.Services.AddCors(options =>
{
options.AddPolicy("MyMyAllowCredentialsPolicy",
builder =>
{
builder.AllowAnyMethod()
.AllowAnyHeader()
.SetIsOriginAllowed(origin => true) // allow any origin
.AllowCredentials(); // allow credentials
}
);
});
然而,我有以下问题: 我尝试了很多不同的配置,但都没有成功。有没有人知道问题在哪里,怎么解决?
提前感谢, Alexia
[版面]
根据所有建议,我改变了我的代码。
前端部分:
const headers = {
'Content-Type': 'application/json;charset=UTF-8',
};
useEffect(() => {
axios.get(baseURL, {
mode: 'cors',
headers: headers,
}).then((response) => {
setAnalysis(response.analysis);
});
}, []);
The back-end :
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
var MyAllowSpecificOrigins = "_myAllowSpecificOrigins";
var builder = WebApplication.CreateBuilder(args);
// Add services to the container.
builder.Services.AddCors(options =>
{
options.AddPolicy(MyAllowSpecificOrigins,
builder =>
{
builder.WithOrigins("http://localhost:3000/")
.AllowAnyHeader()
.AllowAnyMethod();
});
});
builder.Services.AddControllers();
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();
var app = builder.Build();
app.UseCors(MyAllowSpecificOrigins);
// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
app.UseSwagger();
app.UseSwaggerUI();
}
app.UseHttpsRedirection();
app.UseRouting();
app.UseAuthorization();
app.MapControllers();
app.Run();
使用这个配置,我仍然有:
Access to XMLHttpRequest at 'https://localhost:7067/...?id=1' from origin 'http://localhost:3000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
.SetIsOriginAllowed(origin => true)
与.AllowCredentials()
一起使用是不安全的!CORS 不容小觑。 - jub0bsAccess-Control-Allow-*
标头。这些标头是响应标头,而不是请求标头。采取这第一步可能会改善情况。 - jub0bs