Http Post请求不在Angular上发送请求

时间:2018-04-18 10:31:10

标签: c# angular

我正在尝试学习如何使用Http(不是Http客户端)向我的api服务发送http post请求,但是甚至没有收到请求。

网址是正确的,API名称也是正确的(它们匹配)......

从对某些用户的评论中进行的第一次分析,看起来问题与API服务器有某种程度的关系,这是无法访问的,似乎不存在。

你能告诉我我做错了吗?

这是我的代码。

  

REGISTRATION COMPONENT .ts方法(调用USER SERVICE):

registerUser({ value, valid }: { value: UserRegistration, valid: boolean }) {
    this.submitted = true;
    this.isRequesting = true;
    this.errors='';
    if(valid)
    {
        this.userService.register(value.email,value.password,value.firstName,value.lastName,value.location)
                  .finally(() => this.isRequesting = false)
                  .subscribe(
                    result  => {if(result){
                        this.router.navigate(['/login'],{queryParams: {brandNew: true,email:value.email}});                         
                    }},
                    errors =>  this.errors = errors);
    }      
 } 
  

USER SERVICE .ts(由REGISTRATION COMPONENT召集):

register(email: string, password: string, firstName: string, lastName: string,location: string): Observable<UserRegistration> {
let body = JSON.stringify({ email, password, firstName, lastName,location });
let headers = new Headers({ 'Content-Type': 'application/json' });
    let options = new RequestOptions({ headers: headers });

    console.log(this.baseUrl); //URL is correct

return this.http.post(this.baseUrl + "/Accounts/NewUser", body, options)
  .map(res => true)
  .catch(this.handleError);
 }  
  

API方法

[Route("api/[controller]")] 
public class AccountsController : Controller
{
    //...
    // POST api/Accounts/Newuser
    [HttpPost("NewUser")]
    public async Task<IActionResult> NewUser([FromBody]RegistrationViewModel model)
    {
         //....

根据要求:

  

NETWORK CHROME TAB

Network

  

HEADERS DETAILS

Headers

预览显示&#34;无法加载响应数据&#34;

  

CONSOLE ERROR:

Error

按要求:

  

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.SpaServices.Webpack;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.EntityFrameworkCore;
using MyFirstAngularApp.Data;
using MyFirstAngularApp.Models;
using MyFirstAngularApp.Auth;
using Microsoft.Extensions.DependencyInjection.Extensions;
using Microsoft.AspNetCore.Http;
using Microsoft.IdentityModel.Tokens;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using MyFirstAngularApp.Helpers;
using MyFirstAngularApp.Models.Entities;
using Microsoft.AspNetCore.Identity;
using System.Text;
using AutoMapper;
using FluentValidation.AspNetCore;

namespace MyFirstAngularApp
{
    public class Startup
    {
        private const string SecretKey = //MY SECRET KEY
        private readonly SymmetricSecurityKey _signingKey = new SymmetricSecurityKey(Encoding.ASCII.GetBytes(SecretKey));

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

            //connecting to database
            var connectionString = //MY CONNECTION STRING
            services.AddDbContext<MyDataContext>(options => options.UseSqlServer(connectionString));

            //connect to authentication database
            var connectionEntityString = //ANOTHER CONNECION STRING
            services.AddDbContext<ApplicationDbContext>(options => options.UseSqlServer(connectionEntityString));

            //managing tokens
            services.AddSingleton<IJwtFactory, JwtFactory>();

            services.TryAddTransient<IHttpContextAccessor, HttpContextAccessor>();

            // jwt wire up
            // Get options from app settings
            var jwtAppSettingOptions = Configuration.GetSection(nameof(JwtIssuerOptions));

            // Configure JwtIssuerOptions
            services.Configure<JwtIssuerOptions>(options =>
            {
                options.Issuer = jwtAppSettingOptions[nameof(JwtIssuerOptions.Issuer)];
                options.Audience = jwtAppSettingOptions[nameof(JwtIssuerOptions.Audience)];
                options.SigningCredentials = new SigningCredentials(_signingKey, SecurityAlgorithms.HmacSha256);
            });

            var tokenValidationParameters = new TokenValidationParameters
            {
                ValidateIssuer = true,
                ValidIssuer = jwtAppSettingOptions[nameof(JwtIssuerOptions.Issuer)],

                ValidateAudience = true,
                ValidAudience = jwtAppSettingOptions[nameof(JwtIssuerOptions.Audience)],

                ValidateIssuerSigningKey = true,
                IssuerSigningKey = _signingKey,

                RequireExpirationTime = false,
                ValidateLifetime = true,
                ClockSkew = TimeSpan.Zero
            };

            services.AddAuthentication(options =>
            {
                options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
                options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;

            }).AddJwtBearer(configureOptions =>
            {
                configureOptions.ClaimsIssuer = jwtAppSettingOptions[nameof(JwtIssuerOptions.Issuer)];
                configureOptions.TokenValidationParameters = tokenValidationParameters;
                configureOptions.SaveToken = true;
            });

            // api user claim policy
            services.AddAuthorization(options =>
            {
                options.AddPolicy("ApiUser", policy => policy.RequireClaim(Constants.Strings.JwtClaimIdentifiers.Rol, Constants.Strings.JwtClaims.ApiAccess));
            });

            // add identity
            var builder = services.AddIdentityCore<AppUser>(o =>
            {
                // configure identity options
                o.Password.RequireDigit = false;
                o.Password.RequireLowercase = false;
                o.Password.RequireUppercase = false;
                o.Password.RequireNonAlphanumeric = false;
                o.Password.RequiredLength = 6;
            });
            builder = new IdentityBuilder(builder.UserType, typeof(IdentityRole), builder.Services);
            builder.AddEntityFrameworkStores<ApplicationDbContext>().AddDefaultTokenProviders();

            services.AddAutoMapper();
            services.AddMvc().AddFluentValidation(fv => fv.RegisterValidatorsFromAssemblyContaining<Startup>());
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
                app.UseWebpackDevMiddleware(new WebpackDevMiddlewareOptions
                {
                    HotModuleReplacement = true
                });
            }
            else
            {
                app.UseExceptionHandler("/Home/Error");
            }

            app.UseStaticFiles();

            app.UseMvc(routes =>
            {
                routes.MapRoute(
                    name: "default",
                    template: "{controller=Home}/{action=Index}/{id?}");

                routes.MapSpaFallbackRoute(
                    name: "spa-fallback",
                    defaults: new { controller = "Home", action = "Index" });
            });
        }
    }
}

2 个答案:

答案 0 :(得分:1)

让您尝试在启动类

中配置
      if (env.IsDevelopment())
  {
    app.UseDeveloperExceptionPage();
  }

  app.UseExceptionHandler(
  builder =>
  {
    builder.Run(
            async context =>
            {
              context.Response.StatusCode = (int)HttpStatusCode.InternalServerError;
              context.Response.Headers.Add("Access-Control-Allow-Origin", "*");

              var error = context.Features.Get<IExceptionHandlerFeature>();
              if (error != null)
              {
                await context.Response.WriteAsync(error.Error.Message).ConfigureAwait(false);
              }
            });
  });

  app.UseDefaultFiles();
  app.UseStaticFiles();
  app.UseMvc();

答案 1 :(得分:0)

我的代码和应用程​​序中存在两个问题:

首先,我没有使用用户Stefan在他的回答中提出的startup.cs配置。

第二个是我将静态端口地址传递给我的URL。
我在服务模块中使用this._apiURI = '/api';代替this._apiURI = 'http://localhost:5000/api';解决了问题

中用户Deadpool的建议