Angular5新增表格数据时出现POST 400(Bad Request)错误求助
Hey there! Let's break down that 400 Bad Request error you're facing when adding a new row to your table in Angular 5—this is a common gotcha for folks new to HTTP requests with Angular, so let's fix it step by step.
First, let's spot the issue in your code
Looking at your newrow method, there's a critical mistake in how you're constructing the POST request:
this._http.post(`${CONFIG.api_url}/newrow/${nameRow}`, JSON.stringify(nameRow))
You're trying to pass your entire Customer DTO directly into the URL path (${nameRow}), which will just convert the object to a string like [object Object]—this is completely invalid for a URL, and your server is rejecting it with a 400 error because it can't parse that malformed request path.
Here's the fixed code
We'll clean up the URL, remove the unnecessary JSON.stringify (Angular's HttpClient handles serializing objects to JSON automatically), and add better error logging to help debug:
newrow(nameRow: Customer): Observable<Customer[]> { // Remove the object from the URL path—only keep the endpoint return this._http.post<Customer[]>(`${CONFIG.api_url}/newrow`, nameRow) .map(res => super.mapResponse<Customer>(res)) .catch(error => { // Log detailed error info to your browser console for debugging console.error("Failed to add new row:", error.error || error.message); return super.mapError(error); }); }
Additional tips to debug further
- Check your browser's DevTools: Open the Network tab (F12), find the failed POST request, and look at:
- The
Request URLto confirm it's formatted correctly - The
Request Bodyto ensure yourCustomerdata is being sent properly - The
Responsetab to see what specific error message your server is sending back (this often tells you exactly what's wrong, like missing required fields)
- The
- Verify your backend API: Make sure your POST endpoint at
/newrowis configured to accept a JSON body of typeCustomer, and that it doesn't expect any URL parameters you're not providing. - Confirm Content-Type: Angular's
HttpClientautomatically sets theContent-Typeheader toapplication/json, but if your parentsuperclass is modifying this, double-check that it's still correct for your API.
内容的提问来源于stack exchange,提问作者donkeykong

