簡體   English   中英

使用 http 訪問 API 時,請求的資源錯誤中不存在“Access-Control-Allow-Origin”標頭

[英]No 'Access-Control-Allow-Origin' header is present on the requested resource error while accessing the API using http

我正在處理以角度創建的文件上傳頁面。 我的 API 是使用 .Net5 創建的。

我正在 localhost http://localhost:4200/ 上的默認端口中查看我的 angular 應用程序,而且我的 API 也在默認端口。 http://localhost:5000 和 http://localhost:5001

在此處輸入圖片說明

這就是我的前端應用程序的樣子。

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

這是我的組件 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];
    }
  }

}

這是我的打字稿文件。

這是我的 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.

這是一個為測試目的而創建的示例應用程序。

這是我的 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" });
        }
    }
}

下面是我的 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();
            });
        }
    }
}

我已經在我的 startup.cs 文件中配置了 CORS。

我的問題是,如果我使用http url 訪問我的 API,它會給我 CORS 錯誤。

截圖如下。 在此處輸入圖片說明

相反,如果我使用https url,它工作正常。

如果有人可以提供這種行為的原因,那將是有幫助的。 我記得在我之前的項目中,我使用 http URL 來訪問 API。 我已經對它們進行了交叉檢查,以確保我沒有遺漏任何東西。 但我什么也沒看到。

我沒有提到的一件事是,我的開發環境是一台帶有 .net cli 和 VS Code 的 Ubuntu 機器。

任何幫助都會有很大幫助。

提前致謝。

您顯然有 cors 錯誤,它實際上來自瀏覽器,與您的代碼無關。 您可以使用一些與 cors 相關的瀏覽器擴展在本地繞過此類錯誤,但是我覺得這是不必要的,因為您仍然可以在 https 上本地訪問您的資源

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM