Я создаю форму регистрации пользователя в Angular, вот код
import { Component } from '@angular/core';
import { AuthService } from '../_services/auth.service';
@Component({
selector: 'app-registration',
templateUrl: './registration.component.html',
styleUrl: './registration.component.css'
})
export class RegistrationComponent {
form: any = {
email: null,
password: null,
accountType: 1,
name: null,
address: null,
phone: null
};
isSuccessful = false;
isSignUpFailed = false;
errorMessage = '';
constructor(private authService: AuthService) { }
onSubmit(): void {
const { email, password, accountType, name, address, phone } = this.form;
this.authService.register(email, password, accountType, name, address, phone).subscribe({
next: data => {
console.log(data);
this.isSuccessful = true;
this.isSignUpFailed = false;
},
error: err => {
this.errorMessage = err.error.message;
this.isSignUpFailed = true;
}
});
}
}
При отправке вызывает мой метод регистрации authService (ниже), который должен вызывать конечную точку регистрации учетной записи в моем API
import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { Observable } from 'rxjs';
import { AccountType } from '../_classes/AccountType';
import { RegisterRequest } from '../_DTOs/RegisterRequest';
const AUTH_API = 'https://localhost:7033/api/account/';
const httpOptions = {
headers: new HttpHeaders({ 'Content-Type': 'application/json' })
};
@Injectable({
providedIn: 'root',
})
export class AuthService {
constructor(private http: HttpClient) { }
register(email: string, password: string, accountType: AccountType, name: string, address: string, phone: string): Observable {
const request: RegisterRequest = {
email: email,
password: password,
accountType: accountType,
name: name,
address: address,
phone: phone
}
return this.http.post(
AUTH_API + 'register-account',
{
request
},
httpOptions
);
}
}
Благодаря точке останова в моем AccountController метод никогда не срабатывает. Вот контроллер
using AML.Server.Interfaces;
using AML.Server.Models;
using Microsoft.AspNetCore.Mvc;
namespace AML.Server.Controllers
{
[Route("api/[controller]")]
[ApiController]
public class AccountController : ControllerBase
{
private readonly IAccountRepository _accountRepository;
public AccountController(IAccountRepository accountRepository)
{
this._accountRepository = accountRepository;
}
[HttpPost]
[Route("register-account")]
public async Task RegisterAccount(RegisterRequest request)
{
bool success = false;
if (request.Email == "abc@hotmail.com")
{
success = true;
}
// Logic going to repo & return success response
return success;
}
}
}
Он выдает 400 плохих ответов, ответ, который я получаю в DevTools:
{
"type": "https://tools.ietf.org/html/rfc9110#section-15.5.1",
"title": "One or more validation errors occurred.",
"status": 400,
"errors": {
"name": [
"The name field is required."
],
"email": [
"The email field is required."
],
"phone": [
"The phone field is required."
],
"address": [
"The address field is required."
],
"password": [
"The password field is required."
]
},
"traceId": "00-ef5889b3c6e2444528b8799e51a3107b-8ca9bab2705e4cc0-00"
}
Похоже, что параметры не проходят, но я не знаю, как решить проблему. Есть ли у кого-нибудь идеи?
Изменить – дополнительная потенциально полезная информация
Запросить полезную нагрузку
{"request":{"email":"abc@hotmail.com","password":"testtest","accountType":1,"name":"Jordan Abc","address":"123 Fake Street","phone":"07123456789"}}
Регистрационная форма HTML
Registration
@if (!isSuccessful) {
Email
@if (email.errors && f.submitted) {
@if (email.errors['required']) {
Email is required
}
@if (email.errors['email']) {
Email must be a valid email address
}
}
Password
@if (password.errors && f.submitted) {
@if (password.errors['required']) {
Password is required
}
@if (password.errors['minlength']) {
Password must be at least 6 characters
}
}
Name
@if (name.errors && f.submitted) {
@if (name.errors['required']) {
Name is required
}
@if (name.errors['minlength']) {
Name is required
}
@if (name.errors['maxlength']) {
Name must be at most 30 characters
}
}
Address
@if (address.errors && f.submitted) {
@if (address.errors['required']) {
Address is required
}
@if (address.errors['minlength']) {
Address is required
}
@if (address.errors['maxlength']) {
Address must be at most 75 characters
}
}
Phone Number
@if (phone.errors && f.submitted) {
@if (phone.errors['required']) {
Phone Number is required
}
@if (phone.errors['tel']) {
Valid UK Phone Number is required
}
@if (phone.errors['pattern']) {
Valid UK Phone Number is required (No spaces)
}
}
Register
@if (f.submitted && isSignUpFailed) {
Signup failed!
{{ errorMessage }}
}
} @else {
Your registration is successful!
}
proxy.conf.js
const { env } = require('process');
const target = env.ASPNETCORE_HTTPS_PORT ? `https://localhost:${env.ASPNETCORE_HTTPS_PORT}` :
env.ASPNETCORE_URLS ? env.ASPNETCORE_URLS.split(';')[0] : 'https://localhost:7033';
const PROXY_CONFIG = [
{
context: [
"/api/*"
],
target,
secure: false,
}
]
module.exports = PROXY_CONFIG;
Подробнее здесь: https://stackoverflow.com/questions/792 ... -post-call
Сервер ASP.NET Core не получает параметры из почтового вызова внешнего интерфейса Angular ⇐ C#
Место общения программистов C#
1731970676
Anonymous
Я создаю форму регистрации пользователя в Angular, вот код
import { Component } from '@angular/core';
import { AuthService } from '../_services/auth.service';
@Component({
selector: 'app-registration',
templateUrl: './registration.component.html',
styleUrl: './registration.component.css'
})
export class RegistrationComponent {
form: any = {
email: null,
password: null,
accountType: 1,
name: null,
address: null,
phone: null
};
isSuccessful = false;
isSignUpFailed = false;
errorMessage = '';
constructor(private authService: AuthService) { }
onSubmit(): void {
const { email, password, accountType, name, address, phone } = this.form;
this.authService.register(email, password, accountType, name, address, phone).subscribe({
next: data => {
console.log(data);
this.isSuccessful = true;
this.isSignUpFailed = false;
},
error: err => {
this.errorMessage = err.error.message;
this.isSignUpFailed = true;
}
});
}
}
При отправке вызывает мой метод регистрации authService (ниже), который должен вызывать конечную точку регистрации учетной записи в моем API
import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { Observable } from 'rxjs';
import { AccountType } from '../_classes/AccountType';
import { RegisterRequest } from '../_DTOs/RegisterRequest';
const AUTH_API = 'https://localhost:7033/api/account/';
const httpOptions = {
headers: new HttpHeaders({ 'Content-Type': 'application/json' })
};
@Injectable({
providedIn: 'root',
})
export class AuthService {
constructor(private http: HttpClient) { }
register(email: string, password: string, accountType: AccountType, name: string, address: string, phone: string): Observable {
const request: RegisterRequest = {
email: email,
password: password,
accountType: accountType,
name: name,
address: address,
phone: phone
}
return this.http.post(
AUTH_API + 'register-account',
{
request
},
httpOptions
);
}
}
Благодаря точке останова в моем AccountController метод никогда не срабатывает. Вот контроллер
using AML.Server.Interfaces;
using AML.Server.Models;
using Microsoft.AspNetCore.Mvc;
namespace AML.Server.Controllers
{
[Route("api/[controller]")]
[ApiController]
public class AccountController : ControllerBase
{
private readonly IAccountRepository _accountRepository;
public AccountController(IAccountRepository accountRepository)
{
this._accountRepository = accountRepository;
}
[HttpPost]
[Route("register-account")]
public async Task RegisterAccount(RegisterRequest request)
{
bool success = false;
if (request.Email == "abc@hotmail.com")
{
success = true;
}
// Logic going to repo & return success response
return success;
}
}
}
Он выдает 400 плохих ответов, ответ, который я получаю в DevTools:
{
"type": "https://tools.ietf.org/html/rfc9110#section-15.5.1",
"title": "One or more validation errors occurred.",
"status": 400,
"errors": {
"name": [
"The name field is required."
],
"email": [
"The email field is required."
],
"phone": [
"The phone field is required."
],
"address": [
"The address field is required."
],
"password": [
"The password field is required."
]
},
"traceId": "00-ef5889b3c6e2444528b8799e51a3107b-8ca9bab2705e4cc0-00"
}
Похоже, что параметры не проходят, но я не знаю, как решить проблему. Есть ли у кого-нибудь идеи?
[b]Изменить – дополнительная потенциально полезная информация[/b]
Запросить полезную нагрузку
{"request":{"email":"abc@hotmail.com","password":"testtest","accountType":1,"name":"Jordan Abc","address":"123 Fake Street","phone":"07123456789"}}
Регистрационная форма HTML
Registration
@if (!isSuccessful) {
@if (email.errors && f.submitted) {
@if (email.errors['required']) {
Email is required
}
@if (email.errors['email']) {
Email must be a valid email address
}
}
Password
@if (password.errors && f.submitted) {
@if (password.errors['required']) {
Password is required
}
@if (password.errors['minlength']) {
Password must be at least 6 characters
}
}
Name
@if (name.errors && f.submitted) {
@if (name.errors['required']) {
Name is required
}
@if (name.errors['minlength']) {
Name is required
}
@if (name.errors['maxlength']) {
Name must be at most 30 characters
}
}
Address
@if (address.errors && f.submitted) {
@if (address.errors['required']) {
Address is required
}
@if (address.errors['minlength']) {
Address is required
}
@if (address.errors['maxlength']) {
Address must be at most 75 characters
}
}
Phone Number
@if (phone.errors && f.submitted) {
@if (phone.errors['required']) {
Phone Number is required
}
@if (phone.errors['tel']) {
Valid UK Phone Number is required
}
@if (phone.errors['pattern']) {
Valid UK Phone Number is required (No spaces)
}
}
Register
@if (f.submitted && isSignUpFailed) {
Signup failed!
{{ errorMessage }}
}
} @else {
Your registration is successful!
}
proxy.conf.js
const { env } = require('process');
const target = env.ASPNETCORE_HTTPS_PORT ? `https://localhost:${env.ASPNETCORE_HTTPS_PORT}` :
env.ASPNETCORE_URLS ? env.ASPNETCORE_URLS.split(';')[0] : 'https://localhost:7033';
const PROXY_CONFIG = [
{
context: [
"/api/*"
],
target,
secure: false,
}
]
module.exports = PROXY_CONFIG;
Подробнее здесь: [url]https://stackoverflow.com/questions/79201427/asp-net-core-server-not-receiving-params-from-angular-frontend-post-call[/url]
Ответить
1 сообщение
• Страница 1 из 1
Перейти
- Кемерово-IT
- ↳ Javascript
- ↳ C#
- ↳ JAVA
- ↳ Elasticsearch aggregation
- ↳ Python
- ↳ Php
- ↳ Android
- ↳ Html
- ↳ Jquery
- ↳ C++
- ↳ IOS
- ↳ CSS
- ↳ Excel
- ↳ Linux
- ↳ Apache
- ↳ MySql
- Детский мир
- Для души
- ↳ Музыкальные инструменты даром
- ↳ Печатная продукция даром
- Внешняя красота и здоровье
- ↳ Одежда и обувь для взрослых даром
- ↳ Товары для здоровья
- ↳ Физкультура и спорт
- Техника - даром!
- ↳ Автомобилистам
- ↳ Компьютерная техника
- ↳ Плиты: газовые и электрические
- ↳ Холодильники
- ↳ Стиральные машины
- ↳ Телевизоры
- ↳ Телефоны, смартфоны, плашеты
- ↳ Швейные машинки
- ↳ Прочая электроника и техника
- ↳ Фототехника
- Ремонт и интерьер
- ↳ Стройматериалы, инструмент
- ↳ Мебель и предметы интерьера даром
- ↳ Cантехника
- Другие темы
- ↳ Разное даром
- ↳ Давай меняться!
- ↳ Отдам\возьму за копеечку
- ↳ Работа и подработка в Кемерове
- ↳ Давай с тобой поговорим...
Мобильная версия