0

Me esta saliendo el siguiente error

Access to XMLHttpRequest at 'http://localhost:59035/api/PaymentDetail' from origin 'http://localhost:4200' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.

estoy tratando se solucionar este error de la siguiente manera

import { PaymentDetail } from './payment-detail.model';
import { Injectable } from '@angular/core';
import { RequestOptions } from '@angular/http';
import { HttpClient, HttpHeaders } from "@angular/common/http";


@Injectable({
  providedIn: 'root'
})
export class PaymentDetailService {
  formData: PaymentDetail= {
    CVV: null,
    CardNumber: null,
    CardOwnerName: null,
    ExpirationDate: null,
    PMId: null
  };

  readonly rootURL = 'http://localhost:59035/api';
  list : PaymentDetail[];


  constructor(private http: HttpClient) { }

    postPaymentDetail() {
      const headers = new Headers();
      headers.append('Access-Control-Allow-Origin','*')
      headers.append('Access-Control-Allow-Methods','GET, POST, PATCH, PUT, DELETE, OPTIONS');
      headers.append('Access-Control-Allow-Headers','Origin, Content-Type, X-Auth-Token');
      headers.append('Content-Type', 'application/json');

         let OPTIONS = new RequestOptions({headers:headers});
return this.http.post(this.rootURL + '/PaymentDetail', this.formData,{headers:headers});
    }

Pero en estas líneas me esta saliendo lo siguiente

introducir la descripción de la imagen aquí

¿Que es lo que debo hacer para solucionar este problema de blocked by CORS, de esta manera si se soluciona?

Angular 7

Cliente

using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using WebAPI.Models;

namespace WebAPI
{
    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.AddDbContext<PaymentDetailContext>(options =>
            options.UseSqlServer(Configuration.GetConnectionString("DevConnection")));
            services.AddCors(options => {
            options.AddDefaultPolicy(
                Builder=>Builder.WithOrigins("http://localhost:4200")
                .AllowAnyMethod().AllowAnyHeader().AllowCredentials().WithMethods("GET","POST","DELETE","PUT")
                );
            });

        }


        //        .AddJsonOptions(options => {
        //    var resolver = options.SerializerSettings.ContractResolver;
        //    if (resolver != null)
        //        (resolver as DefaultContractResolver).NamingStrategy = null;
        //});


        // 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.UseRouting();

            app.UseAuthorization();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllers();
            });
            app.UseCors(options =>
            options.WithOrigins("http://localhost:4200")
            .AllowAnyMethod()
            .AllowAnyHeader());


        }
    }
}
4
  • headers es una variable local no debes usar this para llamarla. Y la política de CORS debe cambiarse en el servidor no en el cliente.
    – Lobos
    Commented el 12 dic. 2020 a las 2:52
  • Si lo siento publique una cosa que estaba ensayando, pero resulta que desde el servidor ya puse el cors Commented el 12 dic. 2020 a las 2:57
  • Mira ahí subí el startup Commented el 12 dic. 2020 a las 2:59
  • 1
    Bueno hay varias formas de hacerlo. Puedes probar con esta guía de microsoft docs.microsoft.com/en-us/aspnet/core/security/…
    – Lobos
    Commented el 12 dic. 2020 a las 4:35

0

Tu Respuesta

By clicking “Publica tu respuesta”, you agree to our terms of service and acknowledge you have read our privacy policy.

Examina otras preguntas con la etiqueta o formula tu propia pregunta.