简体   繁体   中英

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.

I am viewing my angular application in default port on localhost http://localhost:4200/ And my API is at default port too. http://localhost:5000 and 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

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.

// 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

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.

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.

My problem is if I use the http url to access my API, its giving me CORS error.

Screenshot below. 在此处输入图片说明

Instead if I use the https url, its working fine.

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. 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.

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. 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM