【发布时间】:2020-08-27 04:38:36
【问题描述】:
我正在尝试创建一个简单的应用程序来进行一些 AES 加密(工作所需)。我在 ReactJS 中创建了一个小应用程序,它有一个纯文本文本框、一个调用 encrypt 方法的按钮,以及一个显示加密值的只读文本框。
加密方法调用我用 ASP.NET Core(目前位于本地)编写的 API 来测试加密。当我在 Postman 和/或浏览器中执行时,API 成功加密并返回加密值,但是当我通过我的 React 应用程序执行时,它会引发 CORS 错误。
我在创建 API 和 React 方面都非常陌生,所以如果修复非常简单,请提前道歉。
这是我在 API 项目中的Startup 类:
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.AddCors();
services.AddControllers();
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
app.UseCors(
options => options.WithOrigins("https://localhost:5001/encryption/encrypt").AllowAnyMethod()
);
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseHttpsRedirection();
app.UseRouting();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
}
}
然后这是我在 React 应用程序中的 encrypt 方法:
encrypt() {
var plainText = this.textToEncrypt.value;
console.log(plainText);
var requestOptions = {
method: 'GET',
headers: {
'Access-Control-Allow-Origin' : '*'
}
};
fetch("https://localhost:5001/encryption/encrypt?plainText=" + plainText, requestOptions)
.then(response => response.text())
.then(data => this.setState({ encryptedText: data.value }))
// .then(result => console.log(result))
.catch(error => console.log('error', error));
}
这是来自浏览器控制台的错误:
Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at https://localhost:5001/encryption/encrypt?plainText=sample%20text. (Reason: CORS header ‘Access-Control-Allow-Origin’ missing).
【问题讨论】:
-
查看您的网络应用程序和 api 请求中的网络标头。如果您没有看到
Access-Control-Allow-Origin: *,那么您需要再看一下您的配置。 Arm 的回答中描述的代理方法是一种很好的解决方法,可以避免调整网络标头,这对于生产环境来说是一种不安全的方法。 -
和 fwiw,Access-Control-Allow-Origin 是响应标头,而不是请求标头,因此不需要将其包含在您的 fetch 中(它不会有任何影响)。跨度>