[英]No 'Access-Control-Allow-Origin' header is present on the requested resource error while accessing the API using http
I am working on a file upload page created in angular.我正在处理以角度创建的文件上传页面。 My API is created using .Net5.
我的 API 是使用 .Net5 创建的。
I am viewing my angular application in default port on localhost http://localhost:4200/ And my API is at default port too.我正在 localhost http://localhost:4200/ 上的默认端口中查看我的 angular 应用程序,而且我的 API 也在默认端口。 http://localhost:5000 and http://localhost:5001
http://localhost:5000 和 http://localhost:5001
This is how my front end application looks like.这就是我的前端应用程序的样子。
<div class="container justify-content-center" style="padding-left: 10%; padding-right: 10%;">
<form [formGroup]="userRegistrationForm" (ngSubmit)="register()" enctype="multipart/form-data">
<div class="form-group">
<input class="form-control" type="text" formControlName="firstname" placeholder="First Name" >
</div>
<div class="form-group">
<input class="form-control" type="text" formControlName="lastname" placeholder="Last Name" >
</div>
<div class="form-group">
<input class="form-control" type="text" formControlName="email" placeholder="Email" >
</div>
<div class="form-group">
<input class="form-control" type="password" formControlName="password" placeholder="Password" >
</div>
<div class="form-group">
<input class="form-control"
type="file"
formControlName="profilepic"
(change)="onFileChange($event)">
</div>
<div class="form-group text-center">
<button type="submit" class="btn btn-success">Register</button>
</div>
</form>
</div>
This my html page for component这是我的组件 html 页面
import { Component, OnInit } from '@angular/core';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
import { User } from '../_models/User';
import { UserService } from '../_services/user.service';
@Component({
selector: 'app-register',
templateUrl: './register.component.html',
styleUrls: ['./register.component.css']
})
export class RegisterComponent implements OnInit {
userRegistrationForm: FormGroup;
user : User;
FileToUpload: File;
constructor(private fb: FormBuilder
, private userservice: UserService) { }
ngOnInit() {
this.userRegistrationForm = this.fb.group({
firstname: ['', Validators.required],
lastname: ['', Validators.required],
email: ['', Validators.required],
password: ['', Validators.required],
profilepic: [null, Validators.required]
});
}
register(){
debugger;
if(this.userRegistrationForm.valid){
const formData = new FormData();
for (const key of Object.keys(this.userRegistrationForm.value)) {
const value = this.userRegistrationForm.value[key];
if(key=='profilepic')
formData.append(key, this.FileToUpload);
else
formData.append(key, value);
}
this.user = Object.assign({}, this.userRegistrationForm.value);
this.userservice
.register(formData)
.subscribe((data) => {
alert('Success');
}, error => {
debugger;
alert(error)
});
}
}
onFileChange(event : any) {
if (event.target.files.length > 0) {
this.FileToUpload = event.target.files[0];
}
}
}
This is my typescript file.这是我的打字稿文件。
Here is my environment.ts file.这是我的 environment.ts 文件。
// This file can be replaced during build by using the `fileReplacements` array.
// `ng build` replaces `environment.ts` with `environment.prod.ts`.
// The list of file replacements can be found in `angular.json`.
export const environment = {
production: false,
baseUrl: "https://localhost:5001/"
};
/*
* For easier debugging in development mode, you can import the following file
* to ignore zone related error stack frames such as `zone.run`, `zoneDelegate.invokeTask`.
*
* This import should be commented out in production mode because it will have a negative impact
* on performance if an error is thrown.
*/
// import 'zone.js/plugins/zone-error'; // Included with Angular CLI.
This is a sample application created for testing purpose.这是一个为测试目的而创建的示例应用程序。
Here is my API这是我的 API
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using API.Dtos;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
namespace API.Controllers
{
[ApiController]
[Route("[controller]")]
public class UserController : ControllerBase
{
private readonly ILogger<UserController> _logger;
public UserController(ILogger<UserController> logger)
{
_logger = logger;
}
[HttpPost("Register")]
public IActionResult Register([FromForm]UserDto userDto)
{
return Ok(new { Status="Success", Message="User Added" });
}
}
}
Below is my startup.cs file.下面是我的 startup.cs 文件。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.HttpsPolicy;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using Microsoft.OpenApi.Models;
namespace API
{
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.AddControllers();
services.AddCors();
services.AddSwaggerGen(c =>
{
c.SwaggerDoc("v1", new OpenApiInfo { Title = "API", Version = "v1" });
});
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
app.UseSwagger();
app.UseSwaggerUI(c => c.SwaggerEndpoint("/swagger/v1/swagger.json", "API v1"));
}
app.UseHttpsRedirection();
app.UseRouting();
app.UseCors(x => x.AllowAnyOrigin()
.AllowAnyMethod()
.AllowAnyHeader());
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
}
}
}
I have configured CORS in my startup.cs file.我已经在我的 startup.cs 文件中配置了 CORS。
My problem is if I use the http
url to access my API, its giving me CORS error.我的问题是,如果我使用
http
url 访问我的 API,它会给我 CORS 错误。
Instead if I use the https
url, its working fine.相反,如果我使用
https
url,它工作正常。
If anyone could provide a reason for this behavior it would be helpful.如果有人可以提供这种行为的原因,那将是有帮助的。 I remember in my previous projects I was using http URLs for accessing APIs.
我记得在我之前的项目中,我使用 http URL 来访问 API。 I have cross checked them to ensure I am not missing anything.
我已经对它们进行了交叉检查,以确保我没有遗漏任何东西。 But I am not seeing anything.
但我什么也没看到。
One thing which I missed to mention is that, my development environment is an Ubuntu machine with .net cli and VS Code.我没有提到的一件事是,我的开发环境是一台带有 .net cli 和 VS Code 的 Ubuntu 机器。
Any assistance would be a great help.任何帮助都会有很大帮助。
Thanks in advance.提前致谢。
You're obviously having cors error which is actually coming from the browser and has nothing to do with your code.您显然有 cors 错误,它实际上来自浏览器,与您的代码无关。 you can bypass such errors locally with some cors related browser extensions however I feel it's unnecessary as you can still access your resource locally on https
您可以使用一些与 cors 相关的浏览器扩展在本地绕过此类错误,但是我觉得这是不必要的,因为您仍然可以在 https 上本地访问您的资源
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.