为什么我要收看 Cors Error
Access to XMLHttpRequest at 'http://localhost:5000/api/upload' from origin 'http://localhost:4200' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
据我所理解。在我的启动类中启用了corsasp.net core web api
这是我的代码
public void ConfigureServices(IServiceCollection services)
{
services.AddCors();
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseCors(x => x.AllowAnyOrigin()
.AllowAnyMethod()
.AllowAnyHeader());
app.UseAuthentication();
app.UseMvc();
}
这是我的Angular 7代码
的HTML fileupload
<form [formGroup]="formGroup" (ngSubmit)="onSubmit()">
<div class="form-group">
<input type="file" name="image" />
</div>
<div class="form-group">
<button class="btn btn-primary">Submit</button>
</div>
</form>
这是 fileupload.component.ts
import { Component, OnInit } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { FormGroup, FormControl } from '@angular/forms';
@Component({
selector: 'app-fileupload',
templateUrl: './fileupload.component.html',
styleUrls: ['./fileupload.component.css']
})
export class FileuploadComponent implements OnInit {
fileData: File = null;
formGroup = new FormGroup({
one: new FormControl
});
constructor(private http: HttpClient) { }
fileProgress(fileInput: any) {
this.fileData = <File>fileInput.target.files[0];
}
ngOnInit() {
}
onSubmit() {
const formData = new FormData();
formData.append('file', this.fileData);
this.http.post('http://localhost:5000/api/upload', formData)
.subscribe(res => {
console.log(res);
alert('SUCCESS !!');
})
console.log('Called');
}
}
实际上,我正在按照本教程进行操作:
https://www.tutsmake.com/new-angular-7-upload-file-image-example/
我在Angular 7的帮助下检查文件上传api的部分。我使用邮递员测试了API,到目前为止,它与api中的代码均能正常工作
以下是上传控制器代码
[Produces("application/json")]
[Route("api/[controller]")]
public class UploadController : Controller
{
// GET: /<controller>/
public IActionResult Index()
{
try
{
var file = Request.Form.Files[0];
Console.WriteLine();
return null;
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
Console.WriteLine(ex.StackTrace);
throw ex;
}
}
}
我也收到错误
System.ArgumentOutOfRangeException: 'Index was out of range. Must be non-negative and less than the size of the collection.' on
var file = Request.Form.Files[0];
这是因为Angular 7没有发送数据吗?
非常感谢。
通过CORS策略已阻止从源地址“ http:// localhost:4200 ”访问“ http:// localhost:5000 / api / upload ”处的XMLHttpRequest :要求的资源。
实际上,我怀疑在配置.NET后CORS
是否忘记了重新启动ASP.NET Core Server。
假设您使用的是默认模板,那么您现有的代码对我来说效果很好。如果仍然无法实现,则可以粘贴类的完整代码Startup
。
我也收到错误
System.ArgumentOutOfRangeException: 'Index was out of range. Must be non-negative and less than the size of the collection.' on var file = Request.Form.Files[0];
这是因为Angular 7没有发送数据吗?
是。这是因为在选择文件时尚未绑定事件处理程序来设置fileData
属性。
要解决此问题,请创建一种方法onFileChange(event)
:
@Component({
selector: 'app-fileupload',
templateUrl: './fileupload.component.html',
styleUrls: ['./fileupload.component.css']
})
export class FileuploadComponent implements OnInit {
// ...
onFileChange(event){
this.fileData = <File> event.target.files[0];
}
// ...
}
并如下更改模板:
<form [formGroup]="formGroup" (ngSubmit)="onSubmit()">
<div class="form-group">
<input type="file" name="image" (change)="onFileChange($event)" />
</div>
<div class="form-group">
<button class="btn btn-primary">Submit</button>
</div>
</form>
附带说明,不要在操作方法内将a返回null
为IActionResult
。它将导致未处理的异常:
public IActionResult Index()
{
try
{
var file = Request.Form.Files[0];
Console.WriteLine();
return null; ////////// don't return null
}
catch (Exception ex)
{
// ...
}
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句