当尝试通过调用api上传文件时,它显示错误500服务器错误,并且所请求的资源上没有“ Access-Control-Allow-Origin”标头。因此,不允许访问来源“ http://localhost:5000”。响应的HTTP状态码为500。 这是我的代码。...
component.html
<input type="file" id="file" name=" file" (change)="onFileSelected($event)">
<button type="button" class="btn btn-primary" (click)="onUpload()">Submit </button>
component.ts
selectedFile: File = null;
constructor(private router:Router,private http:HttpClient) { }
onFileSelected(event){
this.selectedFile =<File>event.target.files[0];
console.log(event);
}
onUpload(){
const fd = new FormData();
fd.append('image', this.selectedFile, this.selectedFile.name);
this.http.post('api',fd).subscribe(
response=> {
console.log(response);
});
}
答案 0 :(得分:1)
您需要为您的角度应用程序设置反向代理配置。对于开发,您可以遵循以下指南: https://juristr.com/blog/2016/11/configure-proxy-api-angular-cli/
答案 1 :(得分:0)
请尝试关注...
selectedFile: File = null;
constructor(private router:Router,private http:HttpClient) { }
onFileSelected(event){
this.selectedFile =<File>event.target.files[0];
console.log(event);
}
onUpload(){
const fd = new FormData();
fd.append('image', this.selectedFile, this.selectedFile.name);
let headers = new Headers();
headers.append('Accept', 'application/json');
let options = new RequestOptions({ headers: headers });
this.http.post('api',fd, options).subscribe(
response=> {
console.log(response);
});
}
还,请点击以下链接查看如果api和angular部署在不同域中时如何设置开发服务器代理:
Angular 5 + Spring MVC : getting null http session on server for next request after login
答案 2 :(得分:-1)
如果仅出于测试目的需要它,请为Google Chrome安装CORS插件