Angularhttp 请求

Angular http request

当我发送一个 http post 请求时,我收到两个错误。此请求在 postman 中运行。我在我的 asp 网络核心应用程序中启用了 CORS。 register.component:

import { Component, Inject, OnInit } from '@angular/core';
import { NgForm } from '@angular/forms';
import { User } from '../../interfaces/user';
import { AccountService } from '../../services/account.service';

@Component({
  selector: 'app-register',
  templateUrl: './register.component.html',
  styleUrls: ['./register.component.css']
})
export class RegisterComponent implements OnInit {

  constructor(private _accountService: AccountService) { }



  ngOnInit(): void {
  }

  register(ngForm: NgForm) {
    let response = this._accountService.register(ngForm);
    response.subscribe(data => console.log(data));
  }
}

和account.service:

import { HttpClient } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { NgForm } from '@angular/forms';
import { Observable } from 'rxjs';
import { User } from '../interfaces/user';

@Injectable()
export class AccountService {

  constructor(private http: HttpClient) { }

  private _domain: string = window.location.origin;

  public register(ngForm: NgForm): Observable<object> {
    let userCred = ngForm.value as JSON;
    return this.http.post(this._domain + "/api/account/register", JSON.stringify(userCred));
  }
}

错误:

你可以试试这个。可能有邮递员设置问题

You need to set the content-type in postman as JSON (application/json).
Go to the body inside your POST request, there you will find the raw option.
Right next to it, there will be a drop-down, select JSON (application.json).

可能您需要设置内容类型,如以下代码块所示:

public register(ngForm: NgForm): Observable<object> {
  let userCred = ngForm.value as JSON;
  const httpOptions = { headers: new HttpHeaders({'Content-Type': 'application/json'})     
  return this.http.post(this._domain + "/api/account/register",  
  JSON.stringify(userCred), httpOptions); 
}

您必须添加 header 个选项

const httpOptions = {
  headers: new HttpHeaders({'Content-Type': 'application/json'})
}
  let userCred = ngForm.value as JSON;
    return this.http.post(this._domain + "/api/account/register", JSON.stringify(userCred),httpOptions );