[英]Displaying 400 (bad request) in browser console when performing post method through API in angular 6
通過 REST API 執行 post 方法時顯示 400(錯誤請求)
這是用於運行 ASP.net 的 SQL 服務器。
休息服務.ts
import { Injectable } from '@angular/core';**
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { Observable } from 'rxjs';
import { map } from 'rxjs/operators'
var httpoptions = {
headers: new HttpHeaders({
'Content-Type': 'application/json'
})
}
@Injectable({
providedIn: 'root'
})
員工組件.ts
import { Component, OnInit } from '@angular/core';
import {RestService} from '../rest.service'
@Component({
selector: 'app-employee',
templateUrl: './employee.component.html',
styleUrls: ['./employee.component.css']
})
export class EmployeeComponent implements OnInit {
constructor(public rs:RestService) { }
employees:any
ngOnInit() {
this.funget()
}
funget(){
this.rs.getemployee().subscribe(employees=>{
this.employees=employees
})
}
insert;t1;t2;t3;t4;t5;t6;t7;t8;
funins(){
var data={
ID:this.t1, Name:this.t2,Gender:this.t3,Designation:this.t4,Department:this.t5,EmailID:this.t6,
PhoneNo: this.t7,Address:this.t8}
this.rs.insertemployee(data).subscribe(dt=>{
this.insert=JSON.parse(dt)
this.funget()
})
}
員工控制器.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using System.Web.Http.Cors;
using SampleAPI.Models;
namespace SampleAPI.Controllers
{
[EnableCors(origins: "http://localhost:52821", headers: "*", methods: "*")]
public class EmployeeController : ApiController
{
IEmployeeRepository repository = new EmployeeRepository();
[HttpGet, Route("GetEmployee")]
public IEnumerable<Employee> Get()
{
return repository.GetAll();
}
[HttpGet, Route("GetEmployeeBYID")]
public Employee GetEmployee(int ID)
{
Employee emp = repository.Get(ID);
if (emp == null)
{
throw new HttpResponseException(HttpStatusCode.NotFound);
}
return emp;
}
[HttpPost,Route("InsertEmployee")]
public HttpResponseMessage Post([FromBody] Employee emp)
{
emp = repository.Insert(emp);
var response = Request.CreateResponse<Employee>(HttpStatusCode.Created, emp);
string uri = Url.Link("DefaultApi", new { customerID = emp.ID });
response.Headers.Location = new Uri(uri);
return response;
}
//http://localhost:52821/UpdateEmployee?ID=3
[HttpPut,Route("UpdateEmployee")]
public HttpResponseMessage PutEmployee(int ID,Employee emp)
{
emp.ID = ID;
if (!repository.Update(emp))
{
return Request.CreateErrorResponse(HttpStatusCode.NotFound, " ID :" + ID);
}
else
{
return Request.CreateResponse(HttpStatusCode.OK);
}
}
[HttpDelete,Route("DeleteEmployee")]
public HttpResponseMessage DeleteEmployee(int ID)
{
Employee emp = repository.Get(ID);
if (emp == null)
{
throw new HttpResponseException(HttpStatusCode.NotFound);
}
else
{
if (repository.Delete(ID))
{
return Request.CreateResponse(HttpStatusCode.OK);
}
else
{
return
Request.CreateErrorResponse(HttpStatusCode.NotFound, " ID " + ID);
}
}
}
}
}
輸出
**我希望通過 API 輸出我的帖子數據,但顯示選項http://localhost:52821/InsertEmployee 400(錯誤請求)
從來源“ http://localhost:4200 ”訪問位於“ http://localhost:52821/InsertEmployee ”的 XMLHttpRequest 已被 CORS 策略阻止:對預檢請求的響應未通過訪問控制檢查:它沒有 HTTP好的狀態。
core.js:12501 錯誤 HttpErrorResponse {headers: HttpHeaders, status: 0, statusText: "Unknown Error", URL: null, Ok: false, …}**
問題留在后端,在您的服務器中啟用 CORS 策略。
HTTP OPTIONS 方法用於描述目標資源的通信選項。 客戶端可以為 OPTIONS 方法指定一個 URL,或者一個星號 (*) 來指代整個服務器。 https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods/OPTIONS
var cors = new EnableCorsAttribute("http://srv02:2300", "*", "*");
config.EnableCors(cors);
此錯誤通常表示您傳遞的某種錯誤數據。 這可能是因為某些整數字段值是浮點數,或整數字段值是字符串等。CORS 錯誤理解起來有點復雜,但如果它伴隨着其他一些錯誤,那么通常不是因為服務器上的 CORS 阻塞。
我建議您使用郵遞員並在正文中發送員工數據。 嘗試刪除一個屬性以確定哪個確切的數據格式是錯誤的。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.