出现“Bad Request”的原因可能是由于前端服务调用不正确或后端API接口传参出错导致的。解决方法如下所示:
确认API地址是否正确。
确认前端服务调用的请求方式是否正确。
确认请求参数是否正确传递。例如,前端调用API时未传递必要的参数或者参数类型不正确。
代码示例:
前端服务代码:
import { Injectable } from '@angular/core'; import { HttpClient, HttpHeaders } from '@angular/common/http'; import { Observable } from 'rxjs';
@Injectable() export class MyService{ private baseUrl:string;
constructor(private http: HttpClient){ this.baseUrl = 'http://localhost:5000/api/'; }
getSomething(): Observable
return this.http.post(this.baseUrl + 'getSomething', {}, { headers: headers });
} }
后端API代码:
[Route("api/[controller]")]
[ApiController]
public class MyController : ControllerBase
{
[HttpPost]
[Route("getSomething")]
public ActionResult GetSomething([FromBody] IDictionary
// Do something
return Ok();
}
}
在以上代码示例中,前端服务调用了一个POST请求的API。后端API接口接受了一个范型字典数据。如果未传递任何参数或者传递的参数类型不正确,后端API会返回“Bad Request”。要解决此问题,需要仔细检查所有请求参数,并确保它们在传递给API时是正确的。