httpclient 相关问题

不要使用 - 使用[apache-commons-httpclient],[apache-httpclient-4.x],[java-http-client],[dotnet-httpclient]或[angular-httpclient]

How to post selected checkboxes as an array from angular to api

我在“表单”模块中创建了一个组件“表单页面”: 表单页面.component.html: ... 我在“表单”模块中创建了一个组件“表单页面”: form-page.component.html: <form [formGroup]="form" (submit)="onSubmit()"> <div> <label for="carmodel">Car Model:</label> <input type="text" class="form-control" formControlName="carmodel"> <div *ngIf="form.controls['carmodel'].touched && form.controls['carmodel'].errors"> <div *ngIf="form.controls['carmodel'].hasError('required')" class="error">Carmodel is required.</div> <div *ngIf="form.controls['carmodel'].hasError('minlength')">Carmodel should be minimum 3 characters.</div> </div> </div> <div> <label for="carnum">Car Number:</label> <input type="text" class="form-control" formControlName="carnum"> <div *ngIf="form.controls['carnum'].touched && form.controls['carnum'].errors"> <div *ngIf="form.controls['carnum'].hasError('required')" class="error">carnum is required.</div> </div> </div> <div> <label for="contactNumber">Contact Number:</label> <input type="text" class="form-control" formControlName="contactNumber"> <div *ngIf="form.controls['contactNumber'].touched && form.controls['contactNumber'].errors"> <div *ngIf="form.controls['contactNumber'].hasError('required')" class="error">Contact number is required.</div> </div> </div> <div> <label>Type of Service:</label> <div> <label><input type="radio" name="option" value="Waterwash" formControlName="option"> Waterwash </label> </div> <div> <label><input type="radio" name="option" value="Fullservice" formControlName="option"> Fullservice </label> </div> <div *ngIf="form.controls['option'].touched && form.controls['option'].invalid"> <div class="error">Please select an option</div> </div> </div> <div> <label>Addons:</label> <div> <label><input type="checkbox" value="10%off First service visit" formControlName="checkbox"> 10%off First service visit</label> </div> <div> <label><input type="checkbox" value="10%off Waterwash" formControlName="checkbox"> 10%off Waterwash</label> </div> <div> <label><input type="checkbox" value="Free AC Inspection" formControlName="checkbox"> Free AC Inspection</label> </div> <div *ngIf="form.controls['checkbox'].touched && form.controls['checkbox'].invalid"> <div class="error">Please select at least one Addon</div> </div> </div> <div> <label>State:</label> <select formControlName="state" (change)="onStateChange()"> <option *ngFor="let state of states" [value]="state">{{state}}</option> </select> <div *ngIf="form.controls['state'].touched && form.controls['state'].invalid"> <div class="error">Please select a state</div> </div> </div> <div> <label>City:</label> <select formControlName="city"> <option *ngFor="let city of cities[form.controls['state'].value]" [value]="city">{{city}}</option> </select> <div *ngIf="form.controls['city'].touched && form.controls['city'].invalid"> <div class="error">Please select a city</div> </div> </div> <button type="submit" class="btn btn-primary">Submit</button> <button type="button" (click)="Reset()">Reset</button> <button (click)="goBack()">back</button> </form> form-page.component.ts: import { Component } from '@angular/core'; import { Location } from '@angular/common'; // import { FormGroup, FormBuilder, Validators } from '@angular/forms'; // import { CarServiceService } from 'src/app/services/car-service.service'; @Component({ selector: 'app-form-page', templateUrl: './form-page.component.html', styleUrls: ['./form-page.component.css'] }) export class FormPageComponent { form: FormGroup; states: string[] = ['Tamilnadu', 'Kerala', 'Karnataka','Maharastra']; cities: {[key: string]: string[]} = { 'Tamilnadu': ['Chennai', 'Coimbatore','Madurai'], 'Kerala': ['Trivandrum','Kochi','Kollam'], 'Karnataka': ['Bangalore', 'Mysore'], 'Maharastra': ['Mumbai', 'Pune'] }; constructor(private fb: FormBuilder,private location : Location,private carServiceService :CarServiceService) { this.form = this.fb.group({ carmodel :['', [Validators.required, Validators.minLength(3)]], carnum :['', [Validators.required]], contactNumber: ['', [Validators.required, Validators.pattern(/^\d{10}$/)]], option: ['', Validators.required], checkbox: ['', Validators.required], state: ['', Validators.required], city: ['', Validators.required] }); } goBack():void{ this.location.back(); } onSubmit() { if (this.form.valid) { this.carServiceService.addCar(this.form.value).subscribe(response =>{ console.log(response); }); } else { // Form is invalid, display error messages this.form.markAllAsTouched(); } } Reset(){ this.form.reset(); } onStateChange() { const state = this.form.controls['state'].value; this.form.controls['city'].setValue(''); if (state) { this.form.controls['city'].enable(); } else { this.form.controls['city'].disable(); } } // } 为 POST 创建了一个名为“car-service”的服务: 汽车服务.service.ts: import { Injectable } from '@angular/core'; import { HttpClient } from '@angular/common/http'; import { Observable } from 'rxjs'; @Injectable({ providedIn: 'root' }) export class CarServiceService { constructor(private http: HttpClient) { } addCar(formData : any): Observable<any>{ return this.http.post<any>('https://localhost:7095/api/Forms/submit-form',formData); } } 我正在尝试将表单值发布到 API。当我点击提交时,出现错误 400。 POST https://localhost:7095/api/Forms/submit-form 400 错误: ERROR HttpErrorResponse {headers: HttpHeaders, status: 400, statusText: 'OK', url: 'https://localhost:7095/api/Forms/submit-form', ok: false, …}error: {type: 'https://tools.ietf.org/html/rfc7231#section-6.5.1', title: 'One or more validation errors occurred.', status: 400, traceId: '00-88c37085e17ce434f174cf65d020c28e-1bd09d34125cb2dc-00', errors: {…}}headers: HttpHeaders {normalizedNames: Map(0), lazyUpdate: null, lazyInit: ƒ}message: "Http failure response for https://localhost:7095/api/Forms/submit-form: 400 OK"name: "HttpErrorResponse"ok: falsestatus: 400statusText: "OK"url: "https://localhost:7095/api/Forms/submit-form"[[Prototype]]: 在 asp.net-core web API 中: FormData.cs: namespace AngularApi.Model { public class FormData { public string Carmodel { get; set; } public string Carnum { get; set; } public string ContactNumber { get; set; } public string Option { get; set; } public List<string> Checkbox { get; set; } public string State { get; set; } public string City { get; set; } } } 这是我在 API 中的 FormController: private static List<FormData> formsDataList = new List<FormData>(); [HttpPost("submit-form")] public IActionResult SubmitForm([FromBody] FormData formData) { // process the form data string carmodel = formData.Carmodel; string carnum = formData.Carnum; string contactNumber = formData.ContactNumber; string option = formData.Option; List<string> checkbox = formData.Checkbox; string state = formData.State; string city = formData.City; // validate the form data // if (string.IsNullOrWhiteSpace(carmodel) || string.IsNullOrWhiteSpace(carnum) || string.IsNullOrWhiteSpace(contactNumber) || string.IsNullOrWhiteSpace(option) || checkbox == null || checkbox.Count == 0 || string.IsNullOrWhiteSpace(state) || string.IsNullOrWhiteSpace(city)) // { // return BadRequest(new { Message = " Enter the required fields." }); // } formsDataList.Add(formData); // return Ok(new { Message = "Form submitted successfully." }); return Ok(formData); } 输入甚至没有命中 API。所以我怀疑问题出在 HTTPClient 和复选框上。我想问题出在复选框上。因为如果我从 HTML 表单和 API 中完全删除复选框字段,它会完美地工作并且我能够将值发布到 API。 有人可以告诉我如何解决这个问题。 如果你记录表单值,你会得到这个: carmodel: "kia" ​carnum: "123" ​checkbox: true ​city: "Chennai" ​contactNumber: "456" ​option: "Waterwash" state: "Tamilnadu" 我想你也看到了问题。布尔值不是字符串列表。除此之外,您还为所有三个选项指定了相同的控件名称。 你可以f。 e.使用字符串数组或更好的 FormArray 并使用 ngFor. 生成复选框 首先我定义了复选框值: checkboxes = [ { value: '10%off First service visit', name: '10%off First service visit' }, { value: '10%off Waterwash', name: '10%off Waterwash' }, { value: 'Free AC Inspection', name: 'Free AC Inspection' }, ]; 顺便说一下,将值作为字符串对我来说有点不常见。我的意思是,您宁愿将 id 存储在数据库中。但无论如何。 然后在表单生成器中使用FormArray checkbox: new FormArray([], Validators.required) 并为它创建一个吸气剂 get checkboxesFormArray() { return this.form.controls['checkbox'] as FormArray; } 在那之后填充它 addCheckboxes() { this.checkboxes.forEach(() => this.checkboxesFormArray.push(new FormControl('')) ); } 并添加一个事件处理器来处理checked change事件 checkedChanged(e) { let index = this.checkboxes.findIndex( (item) => item.value === e.target.value ); if (e.target.checked) { this.checkboxesFormArray.controls[index].setValue(e.target.value); } else { this.checkboxesFormArray.controls[index].setValue(''); } } 这是设置 appr 所必需的。控制值到所选字符串。 这就是模板的样子 <div> <label>Addons:</label> <div *ngFor="let cbx of checkboxesFormArray.controls; let i = index"> <label formArrayName="checkbox"> <input type="checkbox" [formControlName]="i" (change)="checkedChanged($event)" [value]="checkboxes[i].value"> {{checkboxes[i].name}} </label> </div> </div> 并且 here 你可以找到一个有效的 stackblitz 演示。 如果这是您要找的,请将其标记为答案。 代替<input type=checkbox>,您可以尝试使用<mat-selection-list>。 将始终返回布尔值。它将返回所选值的数组。 代码将是: <mat-selection-list formControlName="checkbox"> <mat-list-option value="10%off First service visit"> 10%off First service visit</mat-list-option> <mat-list-option value="10%off Waterwash" 10%off Waterwash</label></mat- list-option> <mat-list-option value="Free AC Inspection"> Free AC Inspection</mat- list-option> </mat-selection-list> 注意:MatSelectionList 是 Angular Material 的一个组件。你必须先在你的模块中导入它。

回答 2 投票 0

如何使用 httpClient 从 Exchange 获取数据?

我想从 NSE(印度国家证券交易所)获取数据。 NSE 提供 API 来获取数据。例如 https://www.nseindia.com/api/option-chain-indices?symbol=BANKNIFTY 但如果我去...

回答 1 投票 0

ASP.NET Core Web API - 如何基于 HttpStatus 在第三方 API 中返回响应

在我的 ASP.NET Core-6 Web API 中,我正在使用第三方 API,返回的响应应该基于 Http 状态 我收到了供应商的这些回复: 错误的请求: { “响应 C...

回答 0 投票 0

C# 无法使用 HttpRequestMessage 发布数据并获得 400 状态

我尝试了几种不同的方法我无法让 pipelineId 发布(接收 400),请参见下面的代码: { client.BaseAddress = new Uri(_serviceConfig.DataGapsBaseUrl); 变种请求...

回答 3 投票 0

403 响应 C#, POSTMAN && browser 200, help pls

请帮忙,当用浏览器或邮递员打开链接时,结果是 200 使用 C# 应用程序时 - 403 var client = new HttpClient(); var request = new HttpRequestMessage(HttpMethod.get, "https://api2.stepn.com...

回答 0 投票 0

400 使用 HTTPClient 收到错误请求,但在同一 URL 上与 Postman 一起正常工作

我正在尝试在我的 Springboot 应用程序中使用 HTTPClient 将 JSON POST 请求发送到 URL,但我收到了来自服务器的 400 状态响应。 但是,当我使用

回答 0 投票 0

.Net HTTPClient 第一次请求新客户端很慢,是否可以提高性能

2023-03-30 20:48:52:获取标题所需的时间:501 2023-03-30 20:48:52:获取标题所需的时间:78 2023-03-30 20:48:52:获取标题所需的时间:68 2023-03-30 20...

回答 0 投票 0

C# net 版本 4.8 HttpClient:无法创建 SSL/TLS 安全通道

我想向“https://www.mexc.co/”发送一个简单的请求。 1.net版本4.8 2.本网站使用浏览器轻松打开 3.没有任何ssl验证错误或警告 结果:重新...

回答 1 投票 0

如何向 Micronaut 非声明性 http 客户端添加重试

Micronaut 支持 http 客户端的重试机制,如果我们在这样的声明式客户端中使用它: @Client("http://127.0.0.1:8200") @Retryable(delay = "${retry-delay}", 尝试...

回答 1 投票 0

Android:为 HttpPost 设置连接超时

实际上这是我设置连接超时所必须做的(来自 kuester2000 的这个答案): HttpGet httpPost = new HttpGet("www.xxxx.com/method"); HttpParams http参数 = 新

回答 2 投票 0

Getting 403 Forbidden when using proxy

我尝试在我的应用程序中使用轮换代理。 以下代码有效: var cookies = new CookieContainer(); var proxy = new WebProxy("主机") { 凭证 = 新网络凭证(&

回答 0 投票 0

Observable rxjs 出现 ts httpClient 错误

error: Type 'import("/Users/naym/Documents/pets/angular-nest-todo/node_modules/rxjs/internal/Observable").Observable<{ token: string; }>' 不可分配给类型 'import("/Us. ..

回答 0 投票 0

为什么我尝试从 zip 文件发布内容而不是普通文本文件时得到 404?

我有一个 MVC 跨 Web API 应用程序,它有一个 ApiFileController,标题为: [产生(“应用程序/json”)] [路线(“API/文件”)] 公共类 ApiFileController : ApiBaseController 它...

回答 1 投票 0

如何从 HttpClient 获取 Bearer Token?

我正在尝试通过 HttpClient 发送 POST 请求,但服务器响应显示“未经授权”错误。我如何获得 Bearer Token?我搜索了解决方案,但我不明白.. 那是我的代码...

回答 2 投票 0

在 Angular 14 中,是否可以将拦截器应用于抽象类型的对象?

我正在使用 Angular 14。我有一个抽象模型 导出类 AbstractMyModel { 构造函数(公共公共属性:字符串){ } } 其他模型将从中扩展。有没有办法写...

回答 1 投票 0

Solr6 中插入/更新的未定义字段问题

我正在尝试将 solr 文档插入/更新到 solr 集合中 “ACCT_ID:”1234“ "ACCOUNT_NAME:"测试", "ACCT_地址":"", 在 Solr5 中我没有开始......

回答 0 投票 0

HttpClient 输出有关下载过程的信息

我在 C# 中解决一个问题已经被困了三个星期。即,不久前我在语言文档站点上注意到不建议使用 WebClient 类,最好是...

回答 0 投票 0

如何使用 C# 在 GPT API 中处理会话

通过使用会话,开发人员可以构建聊天应用程序,在与用户的多次交互中保持上下文,这可以带来更吸引人和更自然的对话。 问题:...

回答 0 投票 0

c# .net 6.0 windows 服务 - httpclient 在一段时间后调用抛出超时异常

我有一个 .Net 6.0 windows 服务,每隔几秒就会向 api 发送数据。 Windows服务在一段时间内工作正常。然而,过了一会儿,也许 24 小时后,它突然开始...

回答 1 投票 0

Copy as Curl被屏蔽了,但是Replay没问题,怎么办?

在浏览器开发工具中,比如 chrome 和 edge,我尝试了 Copy as CURL, 复制为卷曲 这个 API 应该返回一个 JSON 正文,但是返回了一些带有 code405 的 HTML,似乎被某些防火墙阻止了。 ...

回答 0 投票 0

© www.soinside.com 2019 - 2024. All rights reserved.